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();
}
}
}
@huotinghh
Copy link

semaphores's performance differs a lot in fair and unfair mode
I use a semaphore in a complex system with 300 permits while the background workflow has 1000 concurrent requests. It takes about 7ms for processing after permit acquired.
For unfair semaphore, the delay for acquiring the permit is less than 1ms while delay for fair semaphore is more than 30ms.
I understand unfair semaphore may have a slightly better performance. But why it differs so much?

@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