Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Timer and thread it creates

I have this question:

I have a timer. With scheduleAtFixedRate it creates a new Timer task. In that timer task there is certain code, which may take a while to complete. How can I make sure that Timer won't create new task when the previous one didn't complete yet?

Thanks

like image 877
Andrey Avatar asked Dec 19 '09 17:12

Andrey


2 Answers

My answer would be to not to use Timer, it's obsolete. Since Java5, Timer has been superseded by the ScheduledExecutorService, which is much more flexible and easier to use. You get finer control over how the scheduler works, the sort of control you don't get with Timer.

You create one using the Executors factory class, which has a number of factory methods. The one you should be looking at is newSingleThreadScheduledExecutor, which should do exactly what you're looking for:

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically. Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.

With a ScheduledExecutorService, instead of subclassing TimerTask, you subclass Runnable directly, and then submit the task to the executor. There are various methods on the executor, you need to pick which one is suitable for your needs (read the javadoc for ScheduledExecutorService carefully), but the gist is something like this:

    // initialise the executor
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    while (tasksRemaining) {
        // create your task
        Runnable task = ....;
        // submit it to the executor, using one of the various scheduleXYZ methods
        executor.schedule(task, delay, unit);
    }

    // when everything is finished, shutdown the executor
    executor.shutdown();

As always, read the javadoc.

like image 183
skaffman Avatar answered Sep 19 '22 10:09

skaffman


The doc for the Timer class

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.

suggests that there's only one background thread. So I believe this scenario won't occur.

like image 42
Brian Agnew Avatar answered Sep 18 '22 10:09

Brian Agnew