开发者

Java: Timer and thread it creates

开发者 https://www.devze.com 2022-12-14 22:26 出处:网络
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 Tim开

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 Tim开发者_JAVA百科er won't create new task when the previous one didn't complete yet?

Thanks


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号