lock object is similar to an implicit lock acquired by a thread to execute a synchronized method or Synchronized block.
lock Interface provides more extensive operations than traditional implicit locks –
Important Method of lock Interface
- void lock()
We can use this method to acquire a lock. If the lock is available, the current thread will get the lock immediately; if the lock is not available, it will wait until getting the lock. It is the same behavior as the traditional Synchronized Keyword
- boolean tryLock()
This method is used to acquire the lock without waiting. If the lock is available then Thread will acquire that lock and return true and if the lock is not available then it returns false, and Thread will continue its execution without waiting. In this case, Thread will never enter into the waiting state.
- boolean tryLock(long time, TimeUnit unit)
By using this method if the lock is available then the Thread will get the lock and continue its execution. If the lock is not available then Thread will wait for a specified time, still if the lock is not available the thread can continue its execution.
- void lockInterruptibly()
This method acquires the lock if it is available and returns immediately. If the lock is not available then it will wait and while waiting if the thread is interrupted then the thread would not get the lock.
- void unlock()
To call this method it is compulsory that the current thread should be the owner of the lock otherwise we will get RunTimeException.
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java
- Threads communication in Java
- Daemon Thread in Java