Reputation: 557
I have a ReentrantReadWriteLock in my application. In the run method of the timertask, I do write lock and then call a function. After that I unlock:
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
lock.writeLock().lock();
function();
lock.writeLock().unlock();
}
}, 0, 1000); // prints 1 every 1second
The thing I'm worried about is what happens if this timer is canceled and the lock is not able to unlock. Is there a way o make it so that calling .cancel will stop the timer only after the current iteration is done.
Or is there another data structure I could use that allows me to, on a separate thread, run a task/function at a certain rate and be able to stop it such that all locks are released?
Upvotes: 0
Views: 1713
Reputation: 14687
The javadoc tells that calling cancel()
won't interrupt a currently running task, so you are safe on this part.
However, I recommand you to use ScheduledThreadPoolExecutor instead of Timer if you can. It's more powerful, simpler to use, and more resilient to potential exceptions thrown by scheduled tasks.
With ScheduledThreadPoolExecutor, you may cancel a particular task by calling cancel(boolean mayInterruptIfRunning)
on the Future returned when scheduling the task, or cancel all scheduled tasks by terminating the scheduler (see shutDown + awaitTermination methods).
If you only need a single thread working on the tasks, you can do so.
I also strongly recommand enclosing lock acquisition and release into a try...finally block. This will make sure that, whenever problem occurs inside the task, the lock will always be released properly. Otherwise, as you have well observed, a problem in the task will prevent the lock from being released.
Upvotes: 1