Multithreading: ReentrantLock.tryLock avoids blocking forever

tryLock(timeout, unit) gives up and returns false instead of waiting indefinitely for a lock that is already held. This lets a thread fail fast or fall back to other work rather than deadlocking.

Code
ReentrantLock lock = new ReentrantLock();
lock.lock();
boolean[] acquired = new boolean[1];
Thread other = new Thread(() -> {
    try {
        acquired[0] = lock.tryLock(10, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) { }
});
other.start();
other.join();
System.out.println("Other thread acquired the held lock: " + acquired[0]);
lock.unlock();
Output
Other thread acquired the held lock: false
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms