views:

347

answers:

9

Java has its own garbage collection implementation so it does not require any destructor like C++ . This makes Java developer lazy in implementing memory management.

Still we can have destructor along with garbage collector where developer can free resources and which can save garbage collector's work. This might improves the performance of application. Why does Java not provide any destructor kind of mechanism?

Developer does not have control over GC but he/she can control or create object. Then why not give them ability to destruct the objects?

+19  A: 

You're asserting that "garbage collection is very expensive" - could you back that up with evidence? Garbage collection is certainly not free but modern garbage collectors are very good.

Note that one of the ways in which the GC is able to be efficient is that it knows it's the only thing doing memory allocation and deallocation (for managed objects). Allowing a developer to explicitly free an object could hamper that efficiency. You'd also need to worry about what would happen if a developer tried to "use" a freed object:

Foo f = new Foo();
Foo g = f;
free(f); // Or whatever
System.out.println(g.toString()); // What should this do?

Are you proposing that each object should have an extra flag for "has this explicitly been freed" which needs to be checked on every dereference? This feels like a recipe for disaster, to be honest.

You're right though - it does allow Java developers to be lazy in this area. That's a good thing. IDEs allow developers to be lazy, too - as do high-level languages, etc. Laziness around memory allocation allows developers in managed environments to spend their energy worrying about business problems rather than memory management.

Jon Skeet
I think developers are lazy (in a good way) by nature!
James B
`free` isn't *free* either.
Tom Hawtin - tackline
A: 

You do have the ability to control object destruction in Java. It simply uses a different idiom:

Connection conn = null;
try {
  conn = ...
  // do stuff
} finally {
  try { conn.close(); } catch (Exception e) { }
}

You could point out at this point that this isn't object destruction and that you could, for example, pass that object to something else and still have a reference to it. You are right on both counts. It is simply as close as Java (and most managed platforms) get.

But no Java does not, as you say, have a destructor mechanism as in C++. Some people mistake finalizers for this. They are not destructors and it is dangerous to use them as such.

Memory management for a programmer is hard. You can easily leak memory, particularly when doing multithreaded programming (also hard). Experience has shown that the cost of GC, while real and sometimes substantial, is well and truly justified in productivity increases and bug incidences in the vast majority of cases, which is why the vast majority of platforms now are "managed" (meaning they use garbage collection).

cletus
That doesn't destroy the *object* - it releases some resources associated with the object (the underlying OS handle, presumably) but not the object itself.
Jon Skeet
A: 

If you know you don't some big objects anymore just set the references to them to null. This could maybe speed up the garbage collection of these objects.

Janusz
Very rarely a good idea, IMO. In most cases the garbage collector is smart enough to work this out for you, and it clutters up your code. There are some exceptions, but they're not very common in my experience.
Jon Skeet
That is right. In most times you don't need this, but it is a possibility for the programmer who thinks he could trick something out of java to do something like freeing a memory.
Janusz
A: 

Imagine the amount of biolerplate code that would be required if you were to write destructors.

Java is designed to be easy to use and understand, so it doesn't have destructors, pointers, and other lower-level stuff.

Effective Java, Chapter 2 proposes some best-practices for object construction and destruction.

Bozho
Expanding on the boilerplate code that Java already requires verges on a crime against humanity! Definitely no destructors, please!
JUST MY correct OPINION
+2  A: 

The C++ destructor is not a way to destruct objects - it's a set of operation that are to be done when the object is destructed. In Java you have no control on the time when objects are destructed (they may be even never destructed), so putting any important code to be executed at object destruction is strongly discouraged (although possible - finalize method). If you ask not for a destructor but for a way to explicitly destroy given object, you are inviting dangling references into your code. They are not welcome.

Tadeusz Kopec
C++ doesn't give you "no control on the time when objects are destructed". C++ uses deterministic finalization. When you delete an object, its destructor is immediately called and then its storage is immediately deallocated. There is no C++ GC. I'm not saying this is necessarily a good thing, but its how C++ works.
Andy Johnson
@andyjohnson: Either you misunderstood me or my grammar was broken. Anyway I tried to fix it. No control on the time when objects are destructed is in Java. In C++ you have full control on it (modulo complicated rules about lifetime of temporaries).
Tadeusz Kopec
@andyjohnson: Storage is immendiately _unavailable_. The actual _deallocation_ may happen later - batch processing is not unheard of.
MSalters
@andy Sure there is a Garbage Collector for C++, it's just not standard: http://www.hpl.hp.com/personal/Hans_Boehm/gc/
FredOverflow
+10  A: 

Garbage Collection is very expensive.

In fact, for complex applications, the performance of garbage collection is competitive with manual storage management based on malloc / free. There is a classic paper by Benjamin Zorn that clearly demonstrates this. In this paper, Zorn describes how he modified some large heap intensive applications to use a conservative garbage collector instead of malloc and free. Then he benchmarked the original and modified versions of the applications. The result was comparable performance.

And note that this was with a 1993 vintage conservative garbage collector. Modern garbage collectors (e.g. Java 6.0's one) are much more efficient.

Stephen C
Thanks buddy...This kind of answer I was expecting
Abhishek Jain
@Abhishek: If you were *expecting* an answer which disputed your assertion, why did you include it as an assertion to start with? Why not just ask "Is garbage collection expensive?" That would come over as less argumentative, IMO.
Jon Skeet
A: 

It's just like... why should we have Government when... I am self disciplined person... why should i pay to Government To maintain something which is not needed by me... ?

So what you say... i am self discipline person... My country should have Government or not...?

mihirpmehta
I know it's hard to digest the comparison but it's same...
mihirpmehta
Actually it's nothing of the sort, but thanks for playing. A better analogy might be "why should we be required to build our own roads all the time when we could let the government do it". And by "better" here I mean "it's still terrible, but better".
JUST MY correct OPINION
I understand your analogy, mihirpmehta, but I don't think it really helps answer the question.
Matthew Flaschen
@Matthew... Actually it helps in answering the question.. because Bragaadeesh thinks every programmer is perfect that's why Java should give Programmers ability to destruct the objects.. rather than managing it by itself...
mihirpmehta
+3  A: 

This makes Java developer lazy in implementing memory management.

No, it releases them to perform useful work.

And Garbage Collection is very expensive.

Compared to what? Facts? Figures? You're about 20 years out of date with that remark. The take-up of Java alone effectively disproves that contention.

This might improves the performance of application.

Or not. Did you have some facts to adduce?

Then why not give them ability to destruct the objects?

Because it's not required?

EJP
A: 

The C++ destructor is not a way to destruct objects - it's a set of operation that are to be done when the object is destructed.

I think you are confusing terminology. Here is how I see it:

create object = first allocate memory, then construct via constructor

destroy object = first destruct via destructor, then deallocate memory

How the memory is allocated and deallocated depends. If you use new and delete, the memory management is done by void* operator new(size_t) and void operator delete(void*).

FredOverflow