1

Suppose I have a static method like this:

public static void doSomething() {
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            something();
        }
    };
    timer.schedule(task, 1000);
}

When the function returns there is no more reference to the timer or the task. Is it possible that they will be garbage collected before the task is allowed to run? If not, why?

kodu
  • 2,176
  • 3
  • 17
  • 22

1 Answers1

0

Your anonymous TimerTask instance has reference to any object used in run(). That means if all objects used in run() are GCed then TimerTask instance can also be GCed.

You can open an debugger on your TimerTask and see it has references to objects used in run().

More info here Do anonymous classes *always* maintain a reference to their enclosing instance?

So in short: GC will not collect any object that is still being used.

Tuby
  • 3,158
  • 2
  • 17
  • 36
  • But if 'something()' is just another static method call, there are no objects used in run() right? So does it get GC? – kodu Nov 22 '18 at 11:42
  • 1
    https://stackoverflow.com/questions/769368/java-why-does-this-not-get-garbage-collected – Tuby Nov 22 '18 at 14:59