How can I interrupt a synchronized statement in Java?

I have two threads that want to synchronize the same object. Thead A should be able to abort Thread B if a certain condition has been filled. Here is some kind of pseudo-code of what these two threads do / should do.

Answer:

 public void run() { while(true) { //Do stuff synchronized(shared) { //Do more stuff if(condition) { B.interrupt(); } } } } 

B:

 public void run() { while(true) { try { //Do stuff synchronized(shared) { //Do more stuff } } catch(InterruptedException e) { continue; } } } 

Here is a situation that I cannot solve:

  • Topic A grabs a shared resource and does some things.
  • Meanwhile, Thread B reaches the synchronized block and expects A free its shared resource.
  • Thread A , doing things, realized that Thread B should not have a shared resource and was trying to abort Thread B But Thread B has already surpassed the points at which an InterruptedException could be thrown.

My question is, is there a way to interrupt a thread while it is waiting for synchronized something?

+7
java multithreading synchronized interrupt
source share
3 answers

For this kind of thing, you should use classes in java.util.concurrent.locks - they have much more features, including intermittent locks.

Edit: If you cannot use these classes, look at jkff's answer - your requirements can be met with mechnism wait() / notify() , but it is easy to introduce subtle errors.

+5
source share

Indeed, you must use locks or implement your stuff using the Object.wait() , Object.notify() and Object.notifyAll() (locks are actually implemented with them). Remember to handle so-called โ€œfalse awakeningsโ€ ( wait() can return even if no one notify() or notifyAll() , so it should always be called in a loop that checks that the condition you expect is satisfied).

+2
source share

No, but ReentrantLock.lockInterruptibly() behaves similarly to the primitive monitorenter instruction and can be interrupted.

+1
source share

All Articles