Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Semaphore — limiting concurrent access

java.util.concurrent.Semaphore limits access using a permit counter. Learn blocking acquire(), nonblocking tryAcquire(), and safe permit return using release().

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Semaphore s = new Semaphore(permits, fair);

s.acquire(); // throws InterruptedException
try {
    // Use the permit.
} finally {
    s.release();
}

boolean acquired = s.tryAcquire();
if (acquired) {
    try {
        // Use the permit.
    } finally {
        s.release();
    }
}

boolean acquiredInTime = s.tryAcquire(timeout, unit); // throws InterruptedException
if (acquiredInTime) {
    try {
        // Use the permit.
    } finally {
        s.release();
    }
}

Semaphore is a counting semaphore: permits limit concurrent access but are not resource objects. new Semaphore(n) is nonfair by default.

Semaphore.acquire() takes a permit, waiting if necessary; it can throw InterruptedException. Semaphore.tryAcquire() immediately returns true after acquisition or false. The timed overload can wait and be interrupted.

Semaphore.release() adds a permit. For resource limiting, call it in finally only after successful acquisition; an extra release increases the limit. A semaphore does not check ownership. Place acquire() before try so interrupted waiting does not cause a release.

new Semaphore(n, true) provides FIFO ordering at internal queueing points, not invocation-start order. The no-argument tryAcquire() does not wait and can take an available permit ahead of queued threads. Actions before release() happen-before actions after successful acquisition in another thread on the same semaphore. The limit alone does not protect resource data structures from races.

Examples

import java.util.concurrent.Semaphore;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Semaphore slots = new Semaphore(1);
        slots.acquire();
        try {
            System.out.println(slots.tryAcquire());
        } finally {
            slots.release();
        }
        if (slots.tryAcquire()) {
            try {
                System.out.println("acquired");
            } finally {
                slots.release();
            }
        }
    }
}

Result

false
acquired

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources