No Idea For Name
No Idea For Name

Reputation: 11577

Java.util.Timer - Process continue when main thread end

I have this simple code using util.Timer

public class CheckDBAccessListOpenAccesses extends TimerTask {
    public static void main(String[] args) {
        CheckDBAccessListOpenAccesses object = new CheckDBAccessListOpenAccesses();
    }

    private CheckDBAccessListOpenAccesses() {

        System.out.println("Start");
        Timer whatAccessAreOpen = new Timer();
        whatAccessAreOpen.scheduleAtFixedRate(this,  TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));
        Thread.sleep(100*60*1000);
        System.out.println("finish");
    }

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

}

When I run the code, the process runs forever. I want the process to stop when the main Thread ends. Why is the Timer keeps the process alive? is there a way to prevent it?

Upvotes: 0

Views: 1428

Answers (2)

Corey D. Holland
Corey D. Holland

Reputation: 46

Java has two types of Threads: user threads and daemon threads. User threads prevent the JVM from terminating, daemon threads do not. By default, a Timer is backed by a user thread, unless it is specified to run as a daemon in the constructor.

To prevent the Timer from keeping the process alive, instantiate the Timer with:

new Timer (true)

See: https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#Timer-boolean-

Upvotes: 3

Mena
Mena

Reputation: 48404

Well, that's in the Timer's API.

The Timer#scheduleAtFixedRate method:

Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

[...]

You may want to use Timer#schedule for one-shot operations, instead.

Otherwise, and what you likely really want, is to have the Timer object visible from your main thread, so you can just invoke Timer#cancel on it when you wish to cancel the scheduled operation, e.g. when your main thread terminates.

Upvotes: 2

Related Questions