91
Java ReentrantLock tryLock() Method
The tryLock() method of ReentrantLock class holds the lock only when any other thread does not hold it at the time of invocation. If the current thread already holds this lock, then the hold count is incremented by one, and the method returns true. Otherwise false.
Syntax
Parameter
timeout – the time to wait for the lock
unit – the time unit of the timeout argument
Returns
true if the lock was free and was acquired by the current thread. Otherwise false.
Throws
InterruptedException – if the current thread is interrupted
NullPointerException – if the time unit is null
Example 1
Output:
Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 task name - Job1 releasing lock(outer lock) Lock Hold Count - 0
Example 2
Output:
Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 task name - Job1 releasing lock(outer lock) Lock Hold Count - 0 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 Thread-1 task name - Job2 releasing lock(outer lock) Lock Hold Count - 0
Next TopicJava ReentrantLock