To understand the working of counting semaphores, i decided to implement a simple version.
I wanted to verify my current implementation is in fact a correct implementation and i havent missed anything obvious
public class CountingSemaphore {
private int limit;
public CountingSemaphore(int limit) {
this.limit = limit;
}
public synchronized void acquire() {
try {
if (limit == 0)
wait();
limit--;
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void release() {
try {
if(limit == 0)
notifyAll();
limit++;
}catch(Exception e) {
e.printStackTrace();
}
}
}
This should work except for one detail.
Since you use
notifyAll(), (and as @JBNizet points out, due to the risk of spurious wakeups,) you can wake up several waiting threads, all of which will be freed and decreaselimit.Change
to
and you should be fine.