Skip to content

Instantly share code, notes, and snippets.

@novln
Created November 8, 2012 20:12
Show Gist options
  • Save novln/4041238 to your computer and use it in GitHub Desktop.
Save novln/4041238 to your computer and use it in GitHub Desktop.
Simple Semaphore Java
package fr.november;
public final class Semaphore {
private final int capacity;
private final Object lock;
private volatile int acquired;
public Semaphore(int capacity) {
this.capacity = capacity;
this.acquired = 0;
this.lock = new Object();
}
public void acquire() throws InterruptedException {
synchronized(lock) {
while(acquired >= capacity) {
lock.wait();
}
acquired++;
}
}
public void release() {
synchronized(lock) {
acquired--;
lock.notify();
}
}
}
@novln
Copy link
Author

novln commented Sep 19, 2019

@huotinghh Fairness ensure that a thread doesn't wait too long if there is a lock congestion, while unfair mode is complete chaos.
In order to accomplish that, we have to monitor how long a thread is waiting to acquire a lock, so it can obtain it in priority.
And this monitoring / priority queue is not free, that's why it differs so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment