views:

77

answers:

4

Is it possible to test for the existence of other references to an object in java?

Even if the operation is inefficient, I would like to assert while debugging that a given object will be garbage collected once a given reference falls out of scope.

Is this possible?

Thanks

A: 

Is it possible to test for the existence of other references to an object in java?

You can debug the code execution and can check that manually i think easily ..

Even if the operation is inefficient, I would like to assert while debugging that a given object will be garbage collected once a given reference falls out of scope.

You can't be 100% sure even your Object is not referred by reference. the GC will collect it.

I would suggest you to go through http://stackoverflow.com/questions/3798424/what-is-the-garbage-collector-in-java and http://stackoverflow.com/questions/1582209/java-garbage-collector-when-does-it-collect

org.life.java
A: 

You can simply override finalize method, then put a breakpoint inside the method. Once the object is garbage collected, you will see in debugger. However please note, that it is highly unwanted to override finalize method in production systems, since it affects badly the GC. So after debugging, remove the method.

Gábor Lipták
"bady affects GC" means that the system gets slower as the Garbage Collector cannot be as efficient.
Thorbjørn Ravn Andersen
Thanks, I think this will do the trick!
Chris
+2  A: 

There is no standard Java API to do so.

Your particular JVM may, however, be able to by using JVM specific diagnostic API's.

Thorbjørn Ravn Andersen
A: 

As Anderson said about the JVM api . The string class uses the intern method to check the object already exists in the pool . They use this API called

   public String intern() {
          return VM.intern(this);
   }

org.apache.harmony.kernel.vm.VM class which is a native code.

Suresh S