views:

338

answers:

10

Is there any possibility that a object which is not referenced anywhere and still existing on heap. I mean is there a possibility that a unused object getting escaped from garbage collector and be there on the heap until the end of the application.

Wanted to know because if it is there, then while coding i can be more cautious.

+5  A: 

If an object is no longer referenced, it does still exist on the heap, but it is also free to be garbage-collected (unless we are talking Class objects, which live in PermGen space and never get garbage-collected - but this is generally not something you need to worry about).

There is no guarantee on how soon that will be, but your application will not run out of memory before memory from those objects is reclaimed.

However, garbage collection does involve overhead, so if you are creating more objects than you need to and can easily create less, then by all means do so.

Edit: in response to your comment, if an object is truly not referenced by anything, it will be reclaimed during garbage collection (assuming you are using the latest JVM from Sun; I can't speak toward other implementations). The reason why is as follows: all objects are allocated contiguously on the heap. When GC is to happen, the JVM follows all references to "mark" objects that it knows are reachable - these objects are then moved into another, clean area. The old area is then considered to be free memory. Anything that cannot be found via a reference cannot be moved. The point is that the GC does not need to "find" the unreferenced objects. If anything, I would be more worried about objects that are still referenced when they are not intended to be, which will cause memory leaks.

danben
thanks danben. but my doubt is, is there any chance that it cannot garbage collected in some unknown scenario.
GK
Garbage collection is very fast these days, particularly for short live objects (trying to reuse objects tends to make things slower, and uglifies code). Some older GC implementations were "conservative" (look it up), and could retain memory by interpreting non-pointer data as a pointer.
Tom Hawtin - tackline
Yes, I should have been more clear - I wasn't advocating reuse over object creation, I was just advocating not creating objects superfluously.
danben
HowTF are we supposed to know what will happen "in some unknown scenario"? Nobody knows about this mysterious scenario, so we certainly can't comment intelligently on it.
Chuck
@gurukulki - see my edit for a deeper explanation.
danben
PermGen space will be garbage collected in modern JVMs, assuming that there are no objects pointing to the class definition. This is pretty much required to allow reloading of J2EE stacks, since what they do is simply throw away the classloader, and then reload all of the classes.
Paul Wagland
@Paul Wagland - I didn't know that. Do you know of a reference that cites this?
danben
@danben: <http://seamframework.org/Community/PermGenSpaceOutOfMemoryError#comment20918> <http://blogs.sun.com/fkieviet/entry/how_to_fix_the_dreaded> -- Note that there is some contention as to whether or not permgen is fixed, but I have definitely seen class definitions being unloaded.
Paul Wagland
Ok, I read the first link and it is clear that this is a special case -- it will ONLY happen when all classes loaded by the ClassLoader become unreachable, which requires that the programmer is using multiple ClassLoaders in the first place.
danben
@danben: correct, they won't normally be garbage collected, but they can be.
Paul Wagland
A: 

This is theoretically possible (there is no guarantee the GC will always find all objects), but should not worry you for any real application - it usually does not happen and certainly does not affect a significant chunk of memory.

ripper234
do you have a reference which states this? I was under the impression that only conservative collectors (boehm, etc) suffer from uncollected objects.
ergosys
Not specifically for Java, but in general:"Tracing garbage collection is not deterministic. An object which becomes eligible for garbage collection will usually be cleaned up eventually, but there is no guarantee when (or even if) that will happen." - http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Determinism
ripper234
+1  A: 

Yes; imagine something like this:

Foo foo = new Foo();

// do some work here

while(1) {};

foo.someOp(); // if this is the only reference to foo,
// it's theoreticaly impossible to reach here, so it
// should be GC-ed, but all GC systems I know of will
// not Gc it

I am using definition of: garbage = object that can never be reached in any execution of the code.

anon
while(1) should read while(true).
Adamski
That code won't compile in java. The compiler will detect the unreachable code and give you an error. Try it. -- Of course if a program gets stuck in an infinite loop while referencing objects then technically the objects are still *referenced* while the point of CG is to remove *unreferenced* objects.
Chad Okere
But that's not the question. gurukulki asked for objects that are not referenced anymore. And `foo` is referenced, though not gc'd. In most real-life applications, a lot (too many) objects are 'unnecessary' from a non-technical standpoint and could be thrown away...
Andreas_D
Not to complain; but why am I downvoted?Even if there are syntactical errors, I highlighted a case of why this can fail.The point is the following: we can't solve the halting problem. Therefore, we can't determine whether certain parts of the code will be executed, therefore there can be objects that will no longer be used ... but we cant tell at any given time based on static analysis techniques.
anon
A: 

In theory, the garbage collector will find all unused objects. There could, of course, be bugs in the garbage collector…

That said, "In theory there is no difference between theory and practice, in practice, there is." Under some, mostly older, garbage collectors, if an object definition manages to reach the permanent generation, then it will no longer be garbage collected under any circumstances. This only applied to Class definitions that were loaded, not to regular objects that were granted tenured status.

Correspondingly, if you have a static reference to an object, that takes up space in the "regular" object heap, this could conceivably cause problems, since you only need to hold a reference to the class definition from your class definition, and that static data cannot be garbage collected, even if you don't actually refer to any instances of the class itself.

In practice though, this is a very unlikely event, and you shouldn't need to worry about it. If you are super concerned about performance, then creating lots of "long-lived" objects, that is, those that escape "escape-analysis", will create extra work for the garbage collector. For 99.99% of coders this is a total non-issue though.

Paul Wagland
+2  A: 

It depends on when and how often the object is used. If you allocate something then deallocate (i.e., remove all references to it) it immediately after, it will stay in "new" part of the heap and will probably be knocked out on the next garbage collection run.

If you allocate an object at the beginning of your program and keep it around for a while (if it survives through several garbage collections), it will get promoted to "old" status. Objects in that part of the heap are less likely to be collected later.

If you want to know all the nitty-gitty details, check out some of Sun's gc documentation.

Seth
You can't 'deallocate' it.
danben
It still will not just "escape" from the garbage collector. The collector will just be less eager to check if it's still being used.
Chuck
@danben - updated.
Seth
@Chuck - true in theory, but it depends on how long the application lives, and the gc parameters. @gurukulki - You can always `-XX:+PrintGCDetails` to see what's actually happening.
Seth
I don't think exiting before the collector has gotten around to collecting an object is what he had in mind when it talked about objects "escaping" from the collector.
Chuck
+2  A: 

If an instance is no longer referenced, it is a possible candidate for garbage collection. This means, that sooner or later it can be removed but there are no guaranties. If you do not run out of of memory, the garbage collector might not even run, thus the instance my be there until the program ends.

The CG system is very good at finding not referenced objects. There is a tiny, tiny chance that you end up keeping a weird mix of references where the garbage collector can not decide for sure if the object is no longer referenced or not. But this would be a bug in the CG system and nothing you should worry about while coding.

phisch
+5  A: 

You should know that, before a JVM throws an out-of-memory exception, it will have garbage collected everything possible.

Steve Emmerson
+1  A: 

Garbage collection intentionally makes few guarantees about WHEN the objects are collected. If memory never gets too tight, it's entirely possible that an unreferenced object won't be collected by the time the program ends.

Steven Sudit
+1  A: 

The garbage collector will eventually reclaim all unreachable objects. Note the "eventually": this may take some time. You can somewhat force the issue with System.gc() but this is rarely a good idea (if used without discretion, then performance may decrease).

What can happen is that an object is "unused" (as in: the application will not use it anymore) while still being "reachable" (the GC can find a path of references from one of its roots -- static fields, local variables -- to the object). If you are not too messy with your objects and structures then you will not encounter such situations. A rule of thumb would be: if the application seems to take too much RAM, run a profiler on it; if thousands of instances of the same class have accumulated without any apparent reason, then there may be some fishy code somewhere. Correction often involves explicitly setting a field to null to avoid referencing an object for too long.

Thomas Pornin
A: 

My advice - Don't worry about it.

Reason - It is possible for a non-referenced object to stay on the heap for some time, but it is very unlikely to adversely affect you because it is guaranteed to be reclaimed before you get an out of memory error.

mikera