×

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

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.