Java — java.util.concurrent.locks.Lock Interface | Code Factory
Index Page : Link
Donate : Link
WordPress Blog : Link
- Lock object is similar to implicit lock aquired by a thread to execute synchronized method or synchronized block.
- Lock implementation provide more extensive operations then traditional implicit locks.
Important methods of Lock interface :
1. void lock()
- We can use this method to aquired a lock. If lock is already available then immediately current thread will get that lock. If the lock is not already available then it will wait until getting a lock. It is exactly same behaviour of traditional synchronized keyword.
2. boolean tryLock()
- To aquire the lock without waiting
- If lock is available then the thread acquire that lock and returns true and if the lock is not available then this method returns false and can contain it’s execution without waiting. In this case thread never be entered into waiting state.
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
3. boolean tryLock(long time, TimeUnit unit) throws InterruptedException
- If lock is available then the thread will get the lock and continue it’s execution.
- If lock is not available then the thread will wait until specified amount of time. Still if the lock is not available then thread can continue it’s execution.
l.tryLock(1, TimeUnit.HOURS)
TimeUnit :
- TimeUnit is an enum present in
java.util.concurrent
.
public enum TimeUnit {
NANOSECONDS,
MICROSECONDS,
MILLISECONDS,
SECONDS,
MINUTES,
HOURS,
DAYS
}
4. void lockInterruptibly() throws InterruptedException
- Aquire the lock if it is available and returns immediately.
- If lock is not available then it will wait.
- While waiting if the thread is interrupted then thread wouldn’t get the lock.
5. void unlock()
- To release a lock.
- To call this method compulsory current thread shouls be owner of the lock otherwise we RE
IllegalMonitorStateException
.