Java GC - 有没有办法确定收集哪些对象 [英] Java GC - is there a way to determine which objects collected

查看:128
本文介绍了Java GC - 有没有办法确定收集哪些对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用-verbosegc标志监控我的应用中的gc活动。我可以看到有完整的和次要的集合,但是有没有一种方法可以确定哪些对象实际收集了哪些对象(获取事件/虚拟标志/其他)?

谢谢! / p>

解决方案

有关内存中对象的一般信息,我建议您查看jvisualvm(它位于JDK的bin文件夹中)。它有很多关于虚拟机在程序运行时所做的有用信息,包括关于各种对象的信息和内存状态。



如果你想要更具体的东西可以使用WeakReferences和ReferenceQueues。如果您只对几种类型的对象感兴趣,则此选项可能是可行的。您可以创建对象的WeakReference,因为它们是使用通用的ReferenceQueue创建的,然后让另一个线程定期检查Queue(请注意,队列只表示对象可达,而不是实际收集的对象):

  static ReferenceQueue< MyObject> MY_QUEUE = new ReferenceQueue< MyObject>(); 
static class MyReference extends WeakReference< MyObject> {
public final String name;
public MyReference(MyObject o,ReferenceQueue< MyObject> q){
super(o,q);
name = o.toString();



static {
Thread t = new Thread(){
public void run(){
while(true) {
MyReference r =(MyReference)MY_QUEUE.remove();
System.out.println(r.name +符合收集条件);
}
}
}
t.setDaemon(true);
t.start();

$ b $ public MyObject(){
//正常初始化...
new MyReference(this,MY_QUEUE);
}


I'm trying to monitor the gc activity in my app, using -verbosegc flag. I can see there are full and minor collections, but is there a way to determine (subscrbing to events/vm flags/whatever) which objects actually collected?

Thanks!

解决方案

For general information about objects in memory I would suggest you look into jvisualvm (it is in the bin folder of your JDK). It has alot of useful information about what the VM is doing as your program runs, including information about the various objects, and memory state.

If you want something more specific you can use WeakReferences and ReferenceQueues. This option might be viable if you are only interested in objects of a few type. You can create a WeakReference to the objects as they are created with a common ReferenceQueue, and then have another thread check the Queue periodically (note that the queue only says the objects are reachable, not that they are actually collected):

static ReferenceQueue<MyObject> MY_QUEUE = new ReferenceQueue<MyObject>();
static class MyReference extends WeakReference<MyObject>{
  public final String name;
  public MyReference(MyObject o, ReferenceQueue<MyObject> q){
    super(o, q);
    name = o.toString();
  }
}

static{
  Thread t = new Thread(){
    public void run(){
      while(true){
        MyReference r = (MyReference)MY_QUEUE.remove();
        System.out.println(r.name+" eligible for collection");
      }
    }
  }
  t.setDaemon(true);
  t.start();
}

public MyObject(){
  //normal init...
  new MyReference(this, MY_QUEUE);
}

这篇关于Java GC - 有没有办法确定收集哪些对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆