Home » Java ReentrantLock tryLock() Method

Java ReentrantLock tryLock() Method

by Online Tutorials Library

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

Test it Now

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

Test it Now

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

You may also like