java synchronization tutorial part 3 using synchronized keyword intrinsic locking

https:‮w//‬ww.theitroad.com

In Part 1 and Part 2 of this synchronization tutorial, we explored ways to achieve thread safety in Java using synchronized blocks and methods, as well as Lock and Condition objects. In this tutorial, we'll dive deeper into the mechanism behind the synchronized keyword and how it achieves intrinsic locking.

When a method or block is marked as synchronized, the Java Virtual Machine (JVM) uses an intrinsic lock, also known as a monitor, to ensure that only one thread can execute the synchronized code at a time. This lock is associated with the object on which the synchronized method or block is called.

Let's take a look at an example:

public synchronized void increment() {
    count++;
}

In this example, the increment method is marked as synchronized, so the JVM will acquire an intrinsic lock on the object on which the method is called before executing the code inside the method. Only one thread can acquire the lock at a time, so if multiple threads attempt to call the increment method on the same object, they will be forced to wait for the lock to be released before executing the method.

The intrinsic lock is automatically acquired when a thread enters a synchronized block or method and is automatically released when the thread exits the block or method. This ensures that the lock is held for the minimum amount of time possible, reducing the risk of deadlock and improving performance.

It's important to note that the intrinsic lock is reentrant, which means that a thread can acquire the lock multiple times without deadlocking. This allows a thread to call a synchronized method from within another synchronized method on the same object without being blocked by the intrinsic lock.

Intrinsic locking is a powerful mechanism for achieving thread safety in Java, but it has some limitations. One major limitation is that it can lead to contention when multiple threads attempt to acquire the same lock. This can lead to decreased performance and even deadlock if not handled properly. It's important to use synchronization sparingly and only when necessary to avoid these issues.

Overall, the synchronized keyword and intrinsic locking mechanism provide a simple and effective way to achieve thread safety in Java. By using synchronized blocks and methods, we can ensure that only one thread can execute critical sections of code at a time, reducing the risk of data corruption and race conditions.