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.
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();
Other thread acquired the held lock: false
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