Saturday, July 5, 2008

What is Reentrant Synchronization in Java?

What is Reentrant Synchronization in Java?

We know that a thread can not acquire a monitor which is owned by another thread. A thread own a monitor for the period between the time it acquires the monitor for entering a synchronized method/block and the time when it releases the monitor when the thread either returns from the method (or completes the block) OR throws an uncaught exception.

But, a thread is allowed to acquire a monitor owned by itself. Confused? Why would a thread need to acquire a monitor which it already owns? It heppens when a synchronized code either directly or indirectly invokes a synchronized method/block which requires the same monitor. For example: a recursive synchronized method. Allowing a thread to acquire the monitor it already owns is called Reentrant Synchronization and without which it'll be very difficult to ensure that a thread in Java doesn't block itself.

Read Next - Synchronization of static fields/methods in Java >> - the article discusses how static methods and static fields are synchronized in Java? How can we ensure exclusive and consistent access to static fields in instance synchronized methods? To understand the why constructors can't be synchronized and how can a half-baked object be exposed to other threads read the article - Why constructors can't be synchronized in Java?


No comments: