Java:为什么这不会被垃圾收集? [英] Java: Why does this not get garbage collected?

查看:109
本文介绍了Java:为什么这不会被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关GCing理论的快速问题。我有以下方法。它运行并退出该方法。即使在GC运行之后,定时器仍然存在并保持TICK状态?我不相信在这个方法存在之后,仍然有对定时器或timertask的引用,所以我期望定时器被GCed并导致异常。请帮我理解这个概念。



谢谢,
jbu

  private void startTimer()
{
Timer timer = new Timer();
TimerTask timerTask = new TimerTask()
{

@Override
public void run()
{
System.out.println() 蜱);
}
};

timer.scheduleAtFixedRate(timerTask,
0,
500);


解决方案

计时器对象实际上调度要在后台线程中执行的任务,以便后台线程维护对Timer(和TimerTask)的引用,从而防止垃圾收集。



以下是文档中的适当引用:
$ b


在最后一次对
Timer对象的实时引用消失并且所有
未完成任务完成
执行时,定时器的任务执行
线程正常终止(并且
受到垃圾
集合的限制)。但是,这可能会花费
任意长。默认情况下,
任务执行线程不会运行
作为守护进程线程,所以它有能力
保持应用程序从
终止。如果调用者想要
终止一个定时器的任务执行
,那么调用者应该
调用定时器的cancel方法。

因此,所有未完成的任务已经完成执行的条件不被满足,并且线程永远不会终止,所以Timer / TimerTask从不被GC_d。


Quick question about the theory of GCing. I have the following method. It runs, and exits the method. How come even after GC is run, the timer still exists and keeps "TICK"ing? I don't believe there's still a reference to timer or the timertask anymore after this method exists, so I'd expect the timer to be GCed and cause an exception. Please help me understand this concept.

Thanks, jbu

private void startTimer()
    {
        Timer timer= new Timer();
        TimerTask timerTask= new TimerTask()
        {

            @Override
            public void run()
            {
                System.out.println("TICK");
            }
        };

        timer.scheduleAtFixedRate(timerTask,
                0,
                500);
    }

解决方案

The Timer object actually schedules tasks to be executed in a background thread, so that background thread maintains a reference to the Timer (and the TimerTask), which prevents both from being garbage-collected.

Here is the appropriate quote from the docs:

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur. By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the the timer's cancel method.

So the condition that "all outstanding tasks have completed execution" is not satisfied, and the thread never terminates, so the Timer/TimerTask is never GC'd.

这篇关于Java:为什么这不会被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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