×

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock and unlock functions all over it. This gives the active thread a lock on the resource and prohibits any other threads from attempting to do so.

ReentrantLock, as its name suggests, enables multiple entries by a thread into the lock on a resource. When the thread initially enters the lock, a hold count is initiated at one. Each time a thread enters lock before being released, the  count goes up by one. When the hold count reaches zero, the resource is released. The count drops by one for each unlocking request.

When a resource is unlocked, reentrant locks also include an option that guarantees that the lock will always allow access to the thread which is waiting. This option is set up by passing true to the function Object() in native code.

Synchronization vs Reentrant Lock:

The synchronised keyword is typically used in Java to create thread synchronisation. The synchronised keyword is rather rigorous in its application, despite the fact that it offers some basic synchronisation. For instance, a thread can only accept a lock once. Because synchronised blocks lack a waiting queue mechanism, any thread can take the lock once a thread exits. This could cause some other thread to run out of resources for a very long time.

Java has reentrant locks to offer synchronisation with more flexibility.

  • Fairness is another important distinction between ReentrantLock and the synchronised keyword. The term "synchronised" opposes fairness. No preference may be provided, and once the lock is released it can be acquired by any thread. ReentrantLock can be made fair by supplying the fairness property when creating an instance of the lock. If there is a dispute, the fairness property grants a lock to the thread that has been waiting for the longest.
  • TryLock() method is the second distinction between synchronised and reentrant locks. A handy tryLock() function is provided by ReentrantLock, which only gets lock if it is available and not being held by another thread. This lessens the blocking caused by threads waiting for Java apps to lock in.
  • Another distinction between ReentrantLock and Java's synchronised keyword is the latter's ability to stop threads while they are waiting for locks. There was no way to prevent a thread from becoming stuck waiting for a lock in the case of a synchronised keyword for an endless amount of time. When a thread is waiting for a lock, ReentrantLock's lockInterruptibly() function allows for interruption. If the lock is unavailable for a predetermined amount of time, tryLock() with timeout can be used to time out.

Thus, it is clear that there are several major distinctions between Java's ReentrantLock and the synchronised keyword. In summary, the Lock interface offers a great deal of flexibility and power and gives users considerable control over the lock acquisition process. This feature may be used to create extremely scalable Java applications.

The following are some significant Java Lock API interfaces and classes:

  • Lock: This is the Lock API's fundamental interface. It offers all the benefits of a synchronised keyword along with extra options to define unique locking conditions and a timeout functionality for threads to wait for a lock. A few crucial methods are lock(), which acquires the lock, unlock(), tryLock(), which waits for the lock for a predetermined amount of time, and newCondition(), which creates the condition, among others.
  • Condition: Condition objects have the added capability of creating several sets of wait, comparable to the Object wait-notify model. Lock objects always produce a Condition object. Await(), which is comparable to wait() and signal(), signalAll(), which is comparable to notify() and notifyAll() techniques, are a few of the crucial methods.
  • ReadWriteLock: One lock is for read-only activities, and the other is for writing. This lock is known as the ReadWriteLock. As long as there are no writer threads, several reader threads may hold the read lock concurrently. There is an exclusive write lock.
  • ReentrantLock: The Lock interface's most popular implementation class. The Lock interface is implemented by this class in a manner comparable to the synchronised keyword. ReentrantLock has several utility methods to access the threads holding the lock, threads waiting to acquire the lock, etc. in addition to implementing the Lock interface. Because synchronised blocks must have the lock on the same monitor object in order to function, a thread can enter a synchronised block if it has the monitor object lock and another synchronised block needs it. ReentrantLock, I believe, is the name of the class for this reason.

Program:

Import java.io.*;
Import java.util.*;
class ReentrantLock {


ReentrantLock lock = new ReentrantLock();
 int c = 0;


     
     int Count() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " Count: " + count);
            return c++;
        } finally {
            lock.unlock();
        }
     }
     int CountTwo() {
            return c++;
     }


    public static void main(String args[]) {
        ThreadTest cn = new ThreadTest();
        Thread t3 = new Thread() {
            public void run() {
                while (cn.Count() < 6) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();                    }
                }
            }
        };
        Thread t4 = new Thread() {
            public void run() {
                while (counter.getCount() < 4) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
      
        t3.start();
        t4.start();
    }}

Output:

Thread-0 Count: 0
Thread-1 Count: 1
Thread-1 Count: 2
Thread-0  Count: 3

Related Topics

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.