Skip to content

Instantly share code, notes, and snippets.

@ashkrit
Last active March 22, 2016 15:04
Show Gist options
  • Save ashkrit/6988313 to your computer and use it in GitHub Desktop.
Save ashkrit/6988313 to your computer and use it in GitHub Desktop.
private AtomicReferenceArray<Thread> consumerWorker;
@Override
public void block() throws InterruptedException {
boolean parked=false;
for(int index=0;index<consumer;index++)
{
if(consumerWorker.get(index)==null && consumerWorker.compareAndSet(index, null, Thread.currentThread()))
{
parked=true;
LockSupport.park(this);
break;
}
}
if(!parked)
{
//Unable to park because no slots available then park for some time
LockSupport.parkNanos(this, TimeUnit.MILLISECONDS.toNanos(10));
}
}
@Override
public void release() {
for(int index=0;index<consumer;index++)
{
Thread threadToNotify = consumerWorker.get(index);
if(threadToNotify!=null)
{
consumerWorker.set(index, null);
LockSupport.unpark(threadToNotify);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment