Why is there no deterministic object destruction in Java? [duplicate]

I understand and enjoy the benefits of the Garbage Collection in Java. However I don’t understand why there is no way in Java to explicitly (and quickly) destroy an object. Surely this could be useful in some cases, I assume performance-critical software.

It’s true that in Java the GC will delete an object with no existing reference to it, so if I want an object deleted I can set the reference to it to null. But if I understand correctly, it isn’t ensured that the GC will indeed delete the object, at least not immediately. And that’s out of the programmer’s control.

Why is there no way in Java to explicitly destroy objects?

While I understand that Java was designed to be used as a high-level language, that abstracts away some of the technical details from the programmer to make things easier: Java has become one of the most widely used languages, and is used in huge projects. I assume that in huge projects, performance is often an issue. Since Java had grown to become what it is, why wasn’t explicit object destruction added to the language?

8

We have to decouple two concepts here.

As of Java 7, the language does have RAII. It’s called the try-with-resources statement.

static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}

This guarantees that the reader will be closed no matter how the block exits.

Even without using try-with-resources, you can deterministically close a stream by calling br.close() when you want.

What’s not deterministic is deleting the object from memory. That has to wait until there are no more references to the object and the garbage collector notices that. Trying to make that deterministic depends on potentially a lot of the program (e.g. does a listener, the debugger, or a logger still reference the object?) and the garbage collector’s operational details (which GC algorithm is in use? is it a concurrent collector? which generation is the object in? how urgent is collection needed right now? …).

16

I have often pondered the same question.

I was a C++ programmer for many years and an Objective C programmer for many years before that. That experience taught me the discipline to track every object creation and achieve the nirvana of code – to logically assure the ultimate destruction of every created object and buffer.

And what a discipline it was – I could guarantee that I never leaked memory anywhere in my code. But memory leaked! Any library I used was a chink in this armor. Threading was a nightmare!! The discipline was valuable but it just did not solve the problem. Even the most carefully written code would require a restart after a few weeks of continuous running and many apps could not run stably for more than about 24 hours.

The solution is Garbage Collection. It makes everything so easy – you just let go of the memory and it floats off like a Helium-filled balloon to be gathered and recycled.

There are two primary benefits that make it a winner:

  1. It is simple – just let go of the object.
  2. The GC process also compacts your heap.

Now those two alone creates an order of magnitude improvement in the stability of your code and the ease of writing and debugging. The only downside is you have to suffer the indignity of occasionally putting up with the inevitable delay of the GC.

A quick consideration of allowing a mixture of immediate and postponed discard also proves pointless.

Say you have a Map tha you have filled with some data and now you know without a doubt that it will not be needed again. Surely manually freeing it would save you peanuts – just the nodes, not the keys or the values. A tiny gain of some fragmented values.

Bottom line – it’s so simple even an incompetent programmer can write leak-free code.

6

The GC attempts to emulate a world where we never run out of memory, and that’s where the advantages in terms of speed and maintainability come from.

In theory, the garbage collector should know more about whether now is a good time to destroy objects than you will while programming it. Often, programs in languages with less abstraction free memory as soon as possible. However, that’s not always good for performance. So you might free memory later, where the place that the objects are allocated and destroyed is far removed. This increases the potential that the programmer will miss something. So it can be bad for memory usage, since things should be destroyed when the system gets some breathing room rather than in the middle of a high speed loop. But it can be faster that way.

If the garbage collector is able to run in a separate thread and do its work without corrupting the main thread’s memory, then it will be faster than if the main thread handles its memory manually.

In practice, it depends on a lot of different things. Can the process be multithreaded, how much memory is available (less means more collections, more means faster speed), etc. While you can also force garbage collection, that’s a very often misused feature. It may clean up those objects, but many times there are references the programmer didn’t realize they were still using. So forcibly destroying those objects could create problems that wouldn’t become apparent until much later, where the GC knows those objects are still in use.

Combined with recycling, so that the memory for objects doesn’t need to be reallocated unless necessary, you can get much faster processing with a lot less work and a lot better maintainability.

9

Going off of here, which lists the design goals of the Java programming language (emphasis mine):

1.2.2 Robust and Secure

The Java programming language is designed for creating highly reliable software. It provides extensive compile-time checking, followed by a second level of run-time checking. Language features guide programmers towards reliable programming habits.
The memory management model is extremely simple: objects are created with a new operator. There are no explicit programmer-defined pointer data types, no pointer arithmetic, and automatic garbage collection. This simple memory management model eliminates entire classes of programming errors that bedevil C and C++ programmers. You can develop Java code with confidence that the system will find many errors quickly and that major problems won’t lay dormant until after your production code has shipped.

The bolded portion, I think, answers your original question pretty well.

As for the second part of your question, I don’t think I can personally answer that sufficiently. However, googling led me to this answer by Jon Skeet on Stack Overflow. He mentions that deterministic destructors tend to involve reference counting, which impacts performance and fails for cycles, and refers readers to this email by Brain Harry on resource management. I cannot verify myself whether these answers are true, but they both point towards deterministic destructors not being worth implementing, as their flaws outweighed the potential benefits of implementation.

(By the way, I think that the linked sources would provide too much information to be reasonably quoted here. If I should quote them anyways, let me know)

Java makes auto cleanup:

As we all know Garbage collector do the clean up job automatically but WHEN? Every object is eligible for cleanup when it has no links.

Car c1=new Car();---Object 1
c1=new Car(); ---Object 2

In line 2, Object 1 is eligible for garbage collection but this would be collected or not, it depends on many other factors. There are three heap spaces Eden, Survivor, Tenured Generation and JVM always wants a proper balance of memory(a proper saw tooth graph). Every object born in Eden space and follow other heap spaces according to it’s age in program. So when any of these heap spaces fulls GC searches for objects with no links and make the cleanup for those object and shifts the remaining object to next heap space.

That’s why in JDBC if we don’t close Connections, Resultsets, Statements then there is a condition of OutOfMemory.

So JVM follow this type of cleanup management which it successful in most of the cases and there is no need of customized memory management. Even for preventing the cases like JDBC outofmemory problem java introduces try with resources, which frees the object at the end of try’s scope.

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }

Don’t confuse with finalize() method it just calls before garbage collection invocation, it has no connection to customized memory clean like destructors in C++.

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật