Created
November 8, 2012 20:12
-
-
Save novln/4041238 to your computer and use it in GitHub Desktop.
Simple Semaphore Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.