2012-02-01 65 views
3

有什么方法可以让我们找出Java垃圾收集器是否在应用程序运行时运行?如何知道垃圾收集器是否在我的应用程序运行时期间运行?

保罗

+4

该信息将如何有用?也许你可以从一开始就解释你的问题。 – 2012-02-02 00:03:08

+1

只是为了好玩,在你的东西的开头添加以下内容:new Object(){protected void finalize()throws Throwable {System.out.println(“GC was here!:)”);}}; – Gevorg 2012-02-02 05:21:55

+0

您是否试图追查瓶颈并怀疑垃圾收集耗尽了您的时间?你有没有尝试分析你的程序?探查器将允许您查看正在运行的线程,包括垃圾收集发生的时间和时间。 – Dodd10x 2012-02-02 04:32:25

回答

0

我猜你可以用WeakReference

// beginning of application 
    WeakReference<Object> ref = new WeakReference < > (new Object ()) ; 

// .... 

// end of application 
    if (ref . get () == null) { System . out . println ("gc") ; } 
    else { System . out . println ("no gc") ; } 
1
List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); 
for (GarbageCollectorMXBean gcBean : gcBeans) { 
    long numCollections = gcBean.getCollectionCount(); // it's possible for this to return -1 for a given collector 
} 
相关问题