Synchronized Block - Java

I understand that the synchronized block provided in Java is basically an implementation of the reentry mutex. However, is a synchronized block an atom?

So, how are interrupts handled for threads currently executing in a synchronized block - does it just release the lock, returning all changes made so far?

EDIT: As for the interrupt part of the question - how is it usually handled in Java. For example, I see many examples of Java code in which developers catch an interrupt when (say) a thread is in the waiting queue. However, in the catch block, all they do is print, which was caused by an interrupt. I'm more curious about what really happens with this thread? Is waiting queue removed?

+7
source share
3 answers

- atomicity

Synchronized blocks help realize atomicity, but their data operations cannot be atomic. To make stuff in a synchronous block atom, you often use atomic data structures like getters and setters like AtomicBoolean.

There is a cornucopia of large atomic classes, such as int atomic arrays, supported by the latest version of java.

- how interrupts are handled:

Interrupts are clearly not handled by synchronization - synchronous ones only block gaurantee, which, when executed, cannot be re-entered by another thread.

+4
source

However, is a synchronized block an atom?

Yes, a synchronized block ensures that this block and any block that was synchronized on the same object are atomic.

How interrupts are handled:

Interrupts are completely different from Java synchronization. Each thread has an interruptedStatus flag, which is set whenever you call interrupt() on a topic. Methods such as Thread.sleep() raise an InterruptedException if the interrupt flag is set and stops their sleep mode.

Note that Thread.sleep() does not release locks during the wait period. The lock associated with the synchronized block is released only when execution exits the block.

+2
source

Thus, basically, the programmer should catch the interrupt event and refuse blocking if it is inside the synchronized block?

You do not need to handle the lock. As written in JLS 14.18 Synchronized statement :

If the execution of the Block completes normally, then the lock is unlocked, and the synchronized statement completes normally. If the execution of the Block terminates abruptly for any reason, then the lock is unlocked, and then the synchronized statement terminates for the same reason.

+1
source

All Articles