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?

asked Nov 22, 2018 at 11:10

1 Answer 1

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.

answered Nov 22, 2018 at 11:25
Sign up to request clarification or add additional context in comments.

2 Comments

But if 'something()' is just another static method call, there are no objects used in run() right? So does it get GC?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.