Codectionary / Developer documentation / Java

Semaphore Capacity Limits

Semaphore limits concurrent access with permits. Each successful acquisition must be paired with a release, even when the protected operation throws. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

semaphore.acquire(); try { work(); } finally { semaphore.release(); }

Examples

Semaphore Capacity Limits

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.util.concurrent.Semaphore;

public class Main {
  public static void main(String[] args) throws Exception {
    Semaphore slots = new Semaphore(1);
    slots.acquire();
    try {
      System.out.println(slots.availablePermits());
      System.out.println(slots.tryAcquire());
    } finally {
      slots.release();
    }
    System.out.println(slots.availablePermits());
  }
}
  1. Expected output: 0 false 1
  2. The sole permit is unavailable inside the protected section. The failed tryAcquire consumes no permit, so only one release is required.

Best practices

  • Release only permits actually acquired.
  • Use timed acquisition or cancellation policies when callers cannot wait indefinitely.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading