← All Exercises

Java Concurrent Locks

advancedjava~30min

Background

Java Lock interface provides more flexibility than synchronized blocks, with tryLock, fairness, and read-write separation.

Problem

Implement a thread-safe counter using ReentrantLock with tryLock for non-blocking attempts and a timeout.

Input

Concurrent calls to increment and getValue from multiple threads.

Output

A consistent counter value reflecting all successful increments.

Sample tests

Sample 1

Input: 100 increments from 10 threads
Expected: 100

Your solution

Learning objective

Learn ReentrantLock, tryLock with timeout, fairness policy, and the lock-try-finally-unlock pattern.