×

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized keyword because locks (and various other more sophisticated synchronization methods) are made using synchronized blocks.

You might not need to implement your locks because Java 5's java.util.concurrent.locks package already includes several lock implementations. However, one will still be required to understand how to utilize them, and understanding the theory underlying their application can be helpful.

An example of a simple lock in java

public class Counter
{
private int count = 0;
public int inc()
{
    synchronized(this)
{
      return ++count;
    }
  }
} 

In the inc() method, take note of the synchronized(this) section.This block allows only one process at a time to execute the return ++count.The synchronized block's code might have been more complex, but the straightforward ++count makes its point.

The methods used in the concept of java lock are

  • lock()
  • lockInterruptibly()
  • newCondition()
  • tryLock()
  • tryLock(long time, TimeUnit unit)
  • unlock()

lock() method

One of the most crucial functions of the Lock connection is the lock() method. It is utilized to obtain the lock. When the lock is unavailable, the current thread is disabled for scheduling purposes. A public method with the return value void is the lock().

Syntax

void lock()

Implementation of lock() method

Incorrect usage of the locking, such as an execution that may result in a deadlock, may be detected by a lock implementation, and in such cases, the lock implementation may issue an unchecked exception. That Lock implementation must include documentation of the facts and the kind of exception.

lockInterruptibly() method

This method obtains the lock unless such a running thread is stopped.

Attains the lock if it is accessible and returns immediately.

For thread scheduling, if the locking is not accessible, the current thread turns disabled and stays inactive until one of two items occurs:

The current thread obtains the lock; or

The current thread is interrupted by another thread, and lock acquisition is maintained throughout this interruption.

If the ongoing thread:

  • is entered into this procedure with its interrupted state set; or
  • is stopped when obtaining the lock, and lock acquisition stoppage is encouraged,

The interrupted status of the current thread is then cleared, and InterruptedException is raised.

Syntax

void lockInterruptibly()
                 throws InterruptedException

Implementation of lockInterruptibly() method

In some implementations, it might not be feasible to stop a lock acquisition, and even if it is, it might be a pricey process. The possibility of this should be known to the programmer. When this is the case, an application should document it.

Implementations may prioritize interrupt response over a standard method return.

Incorrect usage of the lock, such as an execution that may result in a deadlock, may be detected by a lock implementation, and in such cases, the lock implementation may issue an unchecked exception. That Lock implementation must include documentation of the facts and the kind of exception.

lockInterruptibly() method throws InterruptedException

i.e, If the current thread is interrupted while obtaining the lock, an InterruptedException will occur

newCondition() method

returns a fresh Condition instance connected to this Lock iteration.

Prior to awaiting the condition, the lock must always be maintained by the active thread. a request to Condition Before waiting, await() will atomically drop the lock and then re-acquire it before the wait ends.

Syntax

Condition newCondition()

Implementation of newCondition() method

The Lock implementation is responsible for defining the precise operation of the Conditional instance and must do so.

returns: For this Lock instance, a new Condition illustration

Throws: Whenever this Lock implementation does not support conditions, UnsupportedOperationException will occur.

tryLock() method

When called, the tryLock() method is mostly used to acquire the lock. Whenever the lock is available, it returns the lock right away along with the Boolean expression true. Whenever the locking is not available, it produces the Boolean expression false.

The Boolean result is returned by the tryLock() function, which accepts no inputs.

It takes possession of the lock if it is free during the time of invoking.

If the lock is accessible, it is taken, and the value true is returned right away. This method will immediately return the result false if the locking is not accessible.

Syntax

booleantryLock()

Implementation of tryLock() method

Lock lock = ...;
      if (lock.tryLock()) {
          try {


          } finally {
lock.unlock();
          }
      } else {


      }

This method makes sure that the lock is released if it was obtained and prevents attempts to unlock it if it was not

It returns true if the locking is properly acquired and false otherwise.

tryLock(long time, TimeUnit unit)

This function calculates instantly with the result true if the lock is open. For the sake of thread scheduling, the current thread is disabled if the lock is not accessible and remains inactive until one of three components occurs:

  • The current thread obtains the lock; or
  • When a different thread interferes with the one that is now running, lock acquisition can be interrupted;
  • The designated waiting period has passed.

The result true is returned if the lock is obtained.

If the running thread:

  • It is entered into this procedure with its interrupted state set; or
  • It is stopped when obtaining the lock, and lock acquisition stoppage is encouraged,
  • The interrupted status of the current thread is then cleared, and InterruptedException is raised.

The result false is returned if the given waiting period has passed. The function will not wait in any way if indeed the time is 0 or less.

Syntax

booleantryLock(long time,
TimeUnit unit)
       throws InterruptedException

Implementation of tryLock(long time, TimeUnit unit) method

In some implementations, it might not be feasible to stop a lock acquisition, and even if it is, it might be a pricey process. The possibility of this should be known to the programmer. When this is the case, an application should document it.

An implementation may prioritize reporting a timeout or reacting to an interrupt above a regular method return.

Incorrect usage of the lock, such as an execution that may result in a deadlock, may be detected by a lock implementation, and in such cases, the lock implementation may issue an unchecked exception. That Lock implementation must include documentation of the facts and the kind of exception.

Parameters are given as

The maximum length of time to wait for the lock

unit - the temporal component of the temporal argument

If indeed the lock was acquired, it will return true; otherwise, it will return false.

If the current thread is interrupted while obtaining the lock, an InterruptedException will occur i.e  it throws an InterruptedException

unlock() method

Another popular technique for unlocking the lock is the unlock() method. A public method called unlock() has no parameters and no return value.

Syntax

Void unlock()

Implementation of unlock() method

A lock mechanism will normally put limitations on which threads can transfer a lock (generally only the lock holder can release a lock), and if the limitation is broken, it may throw an unchecked exception. That Lock implementation must include documentation of all limitations and the type of exception.


Related Topics

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.