Implementing Semaphore for Concurrent Resource Access Control
Semaphore is a synchronization mechanism in multithreaded programming that regulates access to shared resources by limiting the number of concurrent threads. Unlike locks such as ReentrantLock or synchronized blocks, it does not enforce mutual exclusion but shares similarities in menaging resource access through a counter-based system.
A Semaphore maintains a permit counter. Threads call acquire() to obtain a permit; if the counter is zero, the thread blocks until another thread releases a permit via release(), which increments the counter and allows more threads to proceed.
Key APIs
Constructors
- permits: Specifies the number of available permits (resource slots).
- fair: If set to true, ensures that waiting threads are served in FIFO order, prioritizing the longest-waiting thread.
Common Methods
- acquire(): Blocks the calling thread until a permit is available, then acquires it.
- tryAcquire(): Attempts to acquire a permit without blocking; returns false immediately if no permit is available.
- release(): Releases a permit, increasing the counter and potentially unblocking waiting threads.
Example 1: Limiting access to two threads out of ten, with blocking behavior
public class ResourceController {
public static void main(String[] args) throws InterruptedException {
Semaphore accessControl = new Semaphore(2);
for (int idx = 0; idx < 10; idx++) {
new Thread(() -> {
try {
accessControl.acquire();
System.out.println(Thread.currentThread().getName() + " is processing");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
accessControl.release();
}
}, "Worker-" + idx).start();
}
}
}
Example 2: Non-blocking access attempt with error handling for unavailable permits
public class NonBlockingAccess {
public static void main(String[] args) throws InterruptedException {
Semaphore resourceSemaphore = new Semaphore(2);
for (int j = 0; j < 10; j++) {
new Thread(() -> {
if (resourceSemaphore.tryAcquire()) {
try {
System.out.println(Thread.currentThread().getName() + " executing task");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
resourceSemaphore.release();
}
} else {
System.out.println(Thread.currentThread().getName() + " cannot proceed");
}
}, "Task-" + j).start();
}
}
}