简体   繁体   English

gc方法如何工作?

[英]How does gc method work?

public class GarbageC {
public void finalize()
{
System.out.println("Finalize method");  
}
public static void main(String[] args) {
    GarbageC c1=new GarbageC();
    GarbageC c2=new GarbageC();
    c1=null;
    c2=null;
    System.gc();
    System.out.println("abc");
}
}

While I'm debugging this code, the o/p is coming as 当我调试此代码时,o / p即将

Finalize method
Finalize method
abc

and when I run, I get this 当我跑步时,我得到了

abc
Finalize method
Finalize method

Why am I getting different outputs in both the cases 为什么两种情况下我的输出都不同

Calling System.gc() is a request. 调用System.gc()是一个请求。 The runtime doesn't have to do collect garbage in response. 运行时不必做垃圾收集作为响应。 It may full well decide to ignore you. 完全可以决定不理你。 As such, you can't depend on it doing the same thing consistently. 因此,您不能依靠它始终如一地做同样的事情。

Chances are, in debug mode it really does cause a garbage collection to be run. 在调试模式下,确实有可能导致运行垃圾回收。 In non-debug mode it either just doesn't collect the garbage or waits until an opportune moment to do so. 在非调试模式下,它要么不收集垃圾,要么等到适当的时候收集垃圾。

If you run it often enough you could get any of the 3 possible outputs. 如果您经常运行它,则可能会获得3种可能的输出中的任何一种。

The garbage collection process possibly runs in a dedicated thread (at least in any recent VM it will), so the output depends on the speed of each thread (your main thread and the GC thread of the VM). 垃圾回收进程可能在专用线程中运行(至少会在任何最新的VM中运行),因此输出取决于每个线程(您的主线程和VM的GC线程)的速度。

In debug mode, the main thread is significantly slower (you may pause it indefinetly when stepping through the code). 在调试模式下,主线程要慢得多(单步执行代码时,您可以不确定地暂停它)。 Thus the GC overtakes your main thread. 因此,GC超过了您的主线程。 When you simply run the program; 当您仅运行程序时; the main thread will most likely run through to completeion before the VM even attempts to garbage collect. 在VM甚至尝试进行垃圾收集之前,主线程很可能会一直运行到完成。

A call to System.gc() is only a request "hey please do a gc", even if the VM honors it (its not required to), your request will be passed to the GC thread; 调用System.gc()只是一个请求“嘿, 做一个gc”,即使VM认可了它(不需要这样做),您的请求也将传递给GC线程; that involves at least a slight delay before the GC will actually begin work; 在GC实际开始工作之前,至少需要稍作延迟; and some more time until it actually discovers your garbage objects and then finally collects them. 还有一些时间,直到它真正发现您的垃圾对象,然后最终将它们收集起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM