Skip to content

Instantly share code, notes, and snippets.

@ggdio
Created May 22, 2017 21:16
Show Gist options
  • Save ggdio/3ba4ee768d3458c56c8049cf30f503e5 to your computer and use it in GitHub Desktop.
Save ggdio/3ba4ee768d3458c56c8049cf30f503e5 to your computer and use it in GitHub Desktop.
Semaphore controller - Green vs Red light permission
package br.com.ggdio.util.concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
/**
* Semaphore controller
*
* Red Signal - Blocks all threads controlled by this Semaphore
* Green Signal - All threads controlled by this Semaphore are allowed to proceed
*
* @author Guilherme Dio
*
*/
public class Semaphore {
private final ReentrantLock lock = new ReentrantLock();
private CountDownLatch latch;
public Semaphore() {
this(true);
}
public Semaphore(boolean green) {
if(green) {
setGreenSignal();
} else {
setRedSignal();
}
}
private CountDownLatch getLatch() {
try {
lock.lock();
return latch;
} finally {
lock.unlock();
}
}
/**
* Proceed the signal.
* <p>If it's red, then the current thread is locked until it turns green.</p>
* <p>If it's green, then the current thread is allowed to proceed and continue it's execution.</p>
*
*/
public void proceed() {
try {
getLatch().await();
} catch (InterruptedException e) { }
}
/**
* Releases the semaphore
*/
public void setGreenSignal() {
lock.lock();
if(latch != null) {
latch.countDown();
}
latch = new CountDownLatch(0);
lock.unlock();
}
/**
* Blocks the semaphore
*/
public void setRedSignal() {
lock.lock();
latch = new CountDownLatch(1);
lock.unlock();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment