You can, of course, cancel the task using
task.cancel (true)
This is completely legal. But this will interrupt the thread if it is "RUNNING" .
If the thread is waiting to receive an inline lock, then the interrupt request has no effect other than setting the thread's interrupt status. In this case, you cannot do anything to stop it. For an interrupt to occur, the thread must exit the “blocked” state, acquiring the lock it was expecting (which may take more than 5 minutes). This is a limitation of the use of "built-in lock".
However, you can use explicit lock classes to solve this problem. To do this, you can use the "lockInterruptibly" method of the "Lock" interface. "lockInterruptibly" will allow the thread to try to obtain a lock, while remaining dependent on the interrupt. Here is a small example for this:
public void workWithExplicitLock()throws InterruptedException{ Lock lock = new ReentrantLock(); lock.lockInterruptibly()(); try {
}
source share