The problems with Traditional synchronized keyword “
- We are not having any flexibility to try for a lock without waiting
- There is no way to specify maximum waiting time for a Thread to get lock so that thread will wait until getting the lock which may create performance problems which may cause dead lock
- If a Thread releases the lock then which waiting thread will get that lock we are not having any control on this.
- There is no API to list out all waiting threads for a lock
- We use Synchronized keyword at method level or within a method(synchronized block) and it is not possible to use across multiple methods.
- To overcome these problems java 1.5 introduced java.util.concurrent.locks package
- It also provides several enhancement to the programmer to provide more control on concurrency.
Lock Interface
- Lock object is similar to implicit lock acquired by a Thread to execute synchronized method or synchronized block.
- Lock implementations provide more extensive operations that traditional implicit locks.
Important methods of lock interface
• void lock()
We can use this method to acquire a lock. If lock is available then immediately the current thread will get that lock, if the lock is not already available it will wait until getting lock. If behaves exactly like Traditional synchronized keyword.
• boolean tryLock()
1. This method is used to acquire the lock without waiting.
2. If the lock is available then the thread acquires the lock and returns true.
3. If the lock is not available then this method returns false and it can continue its execution without waiting.
4. Using this method thread will never be entered into waiting state.
• boolean tryLock(long time,TimeUnit unit)
1. If lock is available then thread will get the lock and continue its execution
2. If the lock is not available then the thread will wait until specified amount of time.
3. If the lock is not available after the time passes then thread can continue its execution
• void lockInterruptibly()
1. Acquires the lock if it is available and returns immediately.
2. If the lock is not available then it will wait
3. While waiting if the thread is interrupted then thread won’t get the lock
• void unlock()
1. Releases the lock
2. To call this method the current thread should be the owner of the lock otherwise we will get runtime exception saying IllegalMonitorState exception.
TimeUnit
TimeUnit is an enum present in java.util.concurrent package
enum TimeUnit { NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS; }