Site Search:

SemaphoreOnLock.java

SemaphoreOnLock.java

import java.util.concurrent.locks.*;

/**
* SemaphoreOnLock
* <p/>
* Counting semaphore implemented using Lock
* (Not really how java.util.concurrent.Semaphore is implemented)
*/
public class SemaphoreOnLock {
private final Lock lock = new ReentrantLock();
// CONDITION PREDICATE: permitsAvailable (permits > 0)
private final Condition permitsAvailable = lock.newCondition();
private int permits;

SemaphoreOnLock(int initialPermits) {
lock.lock();
try {
permits = initialPermits;
} finally {
lock.unlock();
}
}

// BLOCKS-UNTIL: permitsAvailable
public void acquire() throws InterruptedException {
lock.lock();
try {
while (permits <= 0)
permitsAvailable.await();
--permits;
} finally {
lock.unlock();
}
}

public void release() {
lock.lock();
try {
++permits;
permitsAvailable.signal();
} finally {
lock.unlock();
}
}

public static void main(String...args) {
SemaphoreOnLock sl = new SemaphoreOnLock(2);
for(int i = 0; i < 10; i++) {
int ii = i;
new Thread(() -> {
try {
sl.acquire();
System.out.println("got it " + ii);
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("about to release " + ii);
sl.release();
}
}).start();
}

}
}


The SemaphoreOnLock class is a simple custom implementation of a counting semaphore using an explicit ReentrantLock and a Condition variable. Threads call acquire() to decrement the internal permit count, blocking if no permits are available, and release() to increment the count and signal waiting threads. Unlike java.util.concurrent.Semaphore, which uses lower-level atomic operations and advanced queuing logic for high performance, this version illustrates how a basic semaphore can be built using Lock and Condition. The main() method demonstrates a practical use case, where only two of ten threads are allowed to run concurrently, modeling resource access control. This example reflects principles discussed in Chapter 14 about building custom synchronizers using higher-level concurrency primitives.

No comments:

Post a Comment