Other related question ,is it a good pratice to do destroy object in JVM or leave it to garbage collection to do it
You cannot explicitly destroy an Object in Java. Grabage collection is the only mechanism there is to remove objects and you can't influence through code how this behaves (not in anyway that absolutley guarentees an oject will be removed anyway).
Hi Raj Joe, I think we cannot destroy an object from JVM and force Garbage Collection to do that directly also.
Garbage Collection have own "destroy management" to do that. We only can set or mark an object with null value. Every object that we set with null value, that is eligible to be removed by Garbage Collection. If we dont mark an object with null value, that object will be eligible for garbage collection if that object is not referenced by others object.
the Garbage collecter will destroy that object in the next time of cleaning up
Possibly. But there is absolutely no guarentee. Java is not like VB (for example) where setting an object to null frees it up. Whether or not the GC decides it can destroy the object is more complex than checking its value, indeed the GC can destroy object which have non-null values.
Setting an object to null as a route to destroying an object via the GC is a misconception which comes from the way people typically tend to explain the mechanics of a GC. If anyone ever tries to explain to you how GC works, they will typically mention Reference Counting (as Fisher Daniel does). And it is the simplest way a GC works, but you'll not find it implemented in many JVMs (if indeeed any). Why? well, it's not a fool proof way of GC - what happens if you have two objects which both have references to each other? And its slow, since every object created needs a reference count to be maintained and checked frequently.
Garbage collection is a complex topic. Far better than trying to explicitly destroy object is to be careful how you create them in the first place. [ October 25, 2004: Message edited by: Paul Sturrock ]
You are, however, assured that the jvm will attempt maximal garbage collection before terminating your program for lack of memory.
The only occasion when programmers should want to force early garbage collection is when they are about to enter extremely time-critical code and don't want to be interrupted by a GC cycle. In that case, Sun suggests you call System.gc() repeatedly until no more memory is freed.