0

Here what I need to do is to get all the reference variables pointing an object in java.

class Dummy{
   public static void main(String[] args){
       Object object = new Object();
       Object object1 = object;
       Object object2 = object;
       Object object3 = object;
       Object object4 = object;
       object3 = null;
   }
}

In this example I have created one object of Object class and five reference variables and assigned the same object to all the reference variables. Finally I set object3 to null. Now what I need is to check the name and total reference variables pointing an object.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
Harshit Gupta
  • 719
  • 1
  • 9
  • 26
  • 1
    References aren't *bi-directional*. An Object doesn't point back to a reference ( or rather a variable that points to it). So, given an Object, you can't find all the references that point to it. – TheLostMind Sep 07 '15 at 07:14
  • Read [this SO post](http://stackoverflow.com/questions/5334137/is-it-possible-to-get-the-object-reference-count) which discusses a trick using weak references to sense when an object is nearing garbage collection, and therefore has no references to it. – Tim Biegeleisen Sep 07 '15 at 07:17
  • I don't understand its utility. Could you please tell us as to why do you want to do the above? – Blip Sep 07 '15 at 07:23

1 Answers1

1

There is no way to do this within the context of a running JVM.

It may be possible to do this from a heap dump (e.g. using jhat and friends) or using a profiling / debugging agent. However, identifying >>all<< of the variables that contain references could be tricky, and I'm not aware of any existing tools (debuggers, profilers, etc) that offer that functionality.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216