Java ReentrantLock tryLock() MethodThe 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. SyntaxParametertimeout - the time to wait for the lock unit - the time unit of the timeout argument Returnstrue if the lock was free and was acquired by the current thread. Otherwise false. ThrowsInterruptedException - if the current thread is interrupted NullPointerException - if the time unit is null Example 1Test it NowOutput: 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 2Test it NowOutput: 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
|