Is Java's Timer task guaranteed not to run concurrently? - java

new Timer(...).schedule(task)
Is task guaranteed to be run by a single thread at any given time?

From the Javadoc
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.
So, yes, you get a new Thread (separate from the caller's thread). Every task in that timer shares the same thread.

There is a single thread per Timer, so the answer to your question is yes

Indeed. They all run on a same background thread corresponded to the Timer object in sequence. BUT two different Timer instances will run (I believe) on different threads, so you have to save reference to a timer object to schedule more tasks sequentialy.

Related

Java util Timer - Thread addition

Timer timer = new Timer();
// scheduling the task at interval
timer.schedule(tasknew,100, 100);
If this is added as part of a web-application at the startup, how is the task getting kicked off at the scheduled time? Is a new daemon thread process being created, solely for triggering this task?
I just want to understand if we are creating any additional thread that is responsible for this task threads?
I just wanted to understand if we are creating any additional threads that is responsible for this task threads?
Yes - from the documentation:
Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.

How is Java Timer implemented by the computer?

The articles on the site related to Timer talk about how to use Timer to program.
I ask a different question.
How does Java perform Timer method?
Since it is said to avoid time-consuming work by not to use while loop to check whether the current time is the required time point, I think Timer is not implemented simply by using while loop to continuously checking and comparing the current time to the desired time point.
Thank you!
I think Timer is not implemented simply by using while loop to continuously
checking and comparing the current time to the desired time point.
YES, IT IS. The only optimization is; it is using priority queue based on nextExecutionTime for tasks.
JavaDoc states
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
Timer class contains
TaskQueue which is a priority queue of TimerTasks, ordered on nextExecutionTime.
TimerThread(queue) the timer's task execution thread, which waits (queue.wait()) for tasks on the timer queue.
TimerThread has private void mainLoop() { where continuous while(true) will keep checking the tasks by comparing nextExecutionTime with currentTimeMillis
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
and if it reaches then calling
if (taskFired) // Task fired; run it, holding no locks
task.run();
According for the javadoc
This class does not offer real-time guarantees: it schedules tasks
using the Object.wait(long) method.
If you look in the code you will find a method called main loop. The first couple of lines are copied below.
private void mainLoop() {
while (true) {
try {
And... it uses a while loop inside of it along with Object.wait() to do the waiting.

How to relaunch a TimerTask

I have written a task to send a certain TCP message through a socket. I have a file with a bunch of messages and some timestamps, so I programmed the task as a TimerTask, and I scheduled it with a Timer with the first message timestamp.
When it finishes, the task run method is over, but its associated thread remains, it's not cancelled. If I try to reschedule the task with a new Time, I'm getting an exception telling me that I cannot reschedulle a schedulled or cancelled task.
I also tried cancellig it before rescheduling, but obviously, as the exception told, it remains the same problem.
I can't schedule the task with a constant perior to let it repeat itself, because each message has a time and it is not constant.
How can I reschedule the TimerTask? And by the way, is there any way of waiting for the task to end, just as in socket communications when it blocks with ready method until a message arrives?
A TimerTask is not designed to be rescheduled and it is the Timer that manages the (single) thread.
Use one Timer and many new TimerTasks:
Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially ..
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread [should] terminates gracefully (and becomes subject to garbage collection).
[From each of the schedule methods:]
Throws IllegalStateException if [the TimerTask] was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
If there are indeed many threads spawned by a single Timer, then that would be a bug which is unlikely: make sure there really is only one Timer object being used.
The last question, of how to compose individual events into a workflow, should be a separate post.

TimerTask and Thread

What's the difference between TimerTask and Thread in Java and Groovy?
Both TimerTask and Thread execute asynchronously, but TimerTask is scheduled to execute at fixed intervals while Thread is not. A Thread is a fairly low-level primitive for parallel execution in a shared virtual address space, and it runs whenever it is on the run queue and gets a turn to run; a TimerTask is only eligible to run at the fixed intervals at which it was scheduled to run.
TimerTask and Thread behave identically whether you run them using Groovy or Java.
TimerTask facilitates execution of one-time or recurring tasks using a Timer. TimerTask has really got nothing to do with Threads, apart from the fact that the Timer will execute these tasks in a background thread (though this could be considered an implementation detail of the Timer class).
Thread on the other hand, is a low-level class for doing parallel execution of anything in a separate thread, and doesn't provide any timing or job-scheduling functionality.

Java Concurrent Execution of Thread Task

I have a task that needs to be executed on a schedule. (It basically polls a database looking for a change and then executes code depending on the result). The problem is that I need the polled task to happen even when it is already executing.
So far I have tried using a Timer/TimerTask combo with the scheduleAtFixedRate() method and the ScheduledThreadPoolExecutor/Thread combo with the scheduleAtFixedRate() method.
Both wait for the current scheduled task to complete before running the next. I need to be able to schedule a task to run every 5 seconds and have it run even if the last execution of the task has not yet completed.
Any ideas?
How about using one Timer as the "kick-off" timer, but then a separate thread pool for execution: when the timer ticks, you submit the task to the thread pool for immediate execution. (You may want to tweak the thread pool to have some maximum number of tasks running simultaneously.)

Categories