omkarok joshiok wrote:
I was wondering if there is any way apart from throwing exception from finalize() method.... in which we can prevent JVM from collecting an object..( an object which is not referenced by any code...).. which may lead to memory leak...??
A memory leak is simply an object that is referenced by the program, that the programmer forgot about.
You don't need to play with the finalize method to cause them -- you can accomplish the leak simply by putting objects in some collection that is referenced by some static variable somewhere. This example, may sound extremely silly, but you will be surprised by how often it happens.
omkarok joshiok wrote:My Question is something like this..... Is there any way in which Object which is not referenced by any thread or live code.... may not get garbage collected?
JVM has an Garbage collection mechanism which has evolved over the years. So its less likely that the objects without any valid references will not be garbage collected.
You might come across a situation where in there are multiple objects involved, each connected to the other (like an island), but no valid references to reach to these from the running program. In these cases as well the objects are GCed.
There have been lot of discussions related to garbage collection in the forum- Java in General and Beginners Forum
But why this question? If you're a beginner in the Java, you're rather wasting your time looking for ways that things might not work the way that the documentation says they work.
I'd say its more useful to think about situations where you think objects are eligible for GC, but they don't get reclaimed because you forgot to clear some reference somewhere.