Programmer's Blog

Programmer's reference

Monthly Archives: January 2016

[Java] Semaphore example

ExecutorService executor = Executors.newFixedThreadPool(10);

Semaphore semaphore = new Semaphore(5);

Runnable longRunningTask = () -> {
  boolean permit = false;
  try {
     permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
     if (permit) {
       System.out.println("Semaphore acquired");
       sleep(5);
     } else {
       System.out.println("Could not acquire semaphore");
     }
  } catch (InterruptedException e) {
    throw new IllegalStateException(e);
  } finally {
    if (permit) {
      semaphore.release();
    }
  }
}

IntStream.range(0, 10)
 .forEach(i -> executor.submit(longRunningTask));

stop(executor);