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?