开发者

How can I find objects which are no longer being used?

开发者 https://www.devze.com 2022-12-17 19:22 出处:网络
I\'m working on a big Java project which has been around for a while (i.e. before my time).The program operates in several phases and many objects get retained from the earlier phases and are used in

I'm working on a big Java project which has been around for a while (i.e. before my time). The program operates in several phases and many objects get retained from the earlier phases and are used in later phases. I've found several groups/categories of object which get retained for no good reason but I suspect there are more.

So my question is, are there any good tools which can show me which Obje开发者_Python百科cts haven't been touched since a particular point in time continued not to be touched until the end of the program. I've been using "yourkit" to examine all the objects but it's often unclear whether they need to be retained or not. If I had something which combined the memory calculations/reporting of yourkit with some kind of coverage tool, I'd be a happy man.


A weak reference is used to determine when an object is no longer being referenced.

  // Create the weak reference. 
     ReferenceQueue rq = new ReferenceQueue(); 
     WeakReference wr = new WeakReference(object, rq); 
  // Wait for all the references to the object. 
  try { 
         while (true) 
        {  
              Reference r = rq.remove(); 
              if (r == wr) 
               { // Object is no longer referenced. } 
         } 
     } 
     catch (InterruptedException e) { } 


You can use VisualVM to examine the heap, and to monitor garbage collection. You should be able to set a breakpoint in your program, then take a look for things you suspect shouldn't be kept around and find out what's keeping a reference to them.

I used to use a commercial tool called (JProbe?) that did just what you want, but that was 8-9 years ago, I don't know if it's still available, or what it might be called if it is.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号