Eitanos30
Eitanos30

Reputation: 1439

Is Timer object isn't being collected by garbage collector?

I try to figure the following code:

    package com.company;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
    public static void main(String[] args) {
        Timer T = new Timer();
        TimerTask Birthday = new TimerTask(){
            int i = 5;
            @Override
            public void run(){
                if(i>0){
                    System.out.println(i);
                    i--;
                }
                else{
                    System.out.println("Happy Birthday John Doe");
                    T.cancel();
                }
            }
        };
        Calendar date = Calendar.getInstance();
        date.set(2021, Calendar.OCTOBER, 30,23, 59, 54);
       T.scheduleAtFixedRate(Birthday, date.getTime(), 1000);
    }
}

I have difficult to understand how the following line works:

T.cancel();

Isn't T (Timer) was collected by garbage collector when the main method ends? After all the run method of TimerTask class continue to run after main thread was close and therefore i assume that Timer T object was collected by garbage collector and when running the row T.cancel() a run time exception should appear. Can someone explain me what is wrong with the way i see the things?

Upvotes: 0

Views: 199

Answers (1)

jtahlborn
jtahlborn

Reputation: 53694

The Timer's thread has a reference to the T instance and therefore it will not be garbage collected. An object cannot be garbage collected until it is unreachable to every live thread.

Upvotes: 2

Related Questions