Member-only story

Java Multithreading, Concurrency, and Parallelism — Part 14

KRISHNA KISHORE V

--

The Locks API — Reentrant Locks

We have seen the locking mechanism using the synchronized keyword in previous parts of this series. Much of this mechanism is also provided by the classes and interfaces of java.util.concurrent.locks package(introduced in Java 5). The Lock API implementations from java.util.concurrent.locks package provide more extensive locking operations than those that can be obtained using synchronized keyword.

There are important reasons why we need to go for this package. So, to start with, let’s understand that there are two kinds of locking: Structured and Unstructured.

Structured Locking: Structured locks enforce all lock acquisition and release to occur in a block-structured way: This means two things. First, when multiple locks are acquired they must be released in the opposite order. Second, all locks must be released in the same lexical scope in which they have been acquired.

What we have seen so far with the synchronized constructs is Structured Locking. Consider the code below to understand this better. Assume that we have three synchronized blocks nested in one another as below.

synchronized (L1) {
...
synchronized (L2) {
...
synchronized (L3) {
...
}
}
}

--

--

KRISHNA KISHORE V
KRISHNA KISHORE V

Written by KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer

No responses yet

Write a response