Java: Why does this not get garbage collected?

前端 未结 4 1223
粉色の甜心
粉色の甜心 2021-01-03 18:39

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 \"TI

4条回答
  •  情歌与酒
    2021-01-03 19:20

    Because a Timer has a background thread that continues running:

    Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.

    Since it's a background thread, it continues until the JVM exits or it's stopped.

    Update: a little more on this. A "background thread" is the same thing as a daemon thread -- named by analogy with a BSD daemon process. If you see the javadocs on Thread, you'll find:

    Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

    When your main terminates, all the user threads stop, leaving only daemon threads. The JVM then shuts down. For a good time — if short — call Thread.currentThread().setDaemon(true); from main.

    Update: Ack. I had that almost right. You have to make the timer a daemon at construction time. (Did this change, or did I just have a brain failure?)

    Anyway, here's example code:

    import java.util.*;
    
    class Chatter extends TimerTask {
        public void run(){
            System.err.println("Timer run.");
        }
    }
    
    public class TryThread {
        public static void main(String[] argv){
            // If argument is true, only runs a few times.
            Timer t = new Timer(false);
            t.schedule(new Chatter(), 1L, 1L);
            return ;
        }
    }
    

提交回复
热议问题