Java SE API
ReentrantLock.tryLock(long, TimeUnit)
Attempt timed acquisition; unlock only when successful.
Formal Syntax & Structure
java syntaxjava
boolean tryLock(long timeout, TimeUnit unit) throws InterruptedExceptionParameters & Attributes
| Name | Type | Description |
|---|---|---|
| timeout | long | Maximum waiting time |
| unit | TimeUnit | Time unit for the supplied duration |
Working Example
Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ReentrantLock lock = new ReentrantLock(); int[] count = {0}; ThreadPoolExecutor workers = pool(2, 2); Callable<Void> increment = () -> { if (!lock.tryLock(3, TimeUnit.SECONDS)) throw new TimeoutException(); try { count[0]++; } finally { lock.unlock(); } return null; }; try { Future<Void> a = workers.submit(increment), b = workers.submit(increment); a.get(3, TimeUnit.SECONDS); b.get(3, TimeUnit.SECONDS); System.out.println(count[0]); } finally { stop(workers); } }}