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.