Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized block - Java

I realize that the synchronized block provided in Java is basically an implementation of a re-entrant mutex. However is the synchronized block atomic?

So how are interrupts handled for threads currently executing within the synchronized block - does it simply release the lock by reverting all the changes made so far?

EDIT: With regards to the Interrupts part of the question - how is it generally handled in Java. For instance, I see many java code examples wherein developers catch an interrupt when (say) a thread is in the wait queue. However within the catch block all they do is print that an interrupt has been raised. I am more curious as to what actually happens to that thread? Is it removed from the wait queue?

like image 780
Hari Avatar asked Oct 06 '11 01:10

Hari


1 Answers

-- atomicity

Synchronized blocks help to implement atomicity - but their data operations can't be garaunteed to be atomic. To make the stuff in a synchronized block atomic, you use often use atomic data structures like getters and setters, for example, AtomicBoolean.

There are a cornucopia of great atomic classes, like atomic int arrays, supported by the latest java version.

-- how interrupts are handled :

Interrupts are not explicitly handled by synchronization - synchronous blocks only gaurantee that, while executing, the block cannot be reentered by another thread.

like image 86
jayunit100 Avatar answered Sep 18 '22 18:09

jayunit100