Semaphore Bulk Permits And DrainPermits

Acquire multiple Semaphore permits at once for heavy tasks, then call drainPermits to seize remaining capacity before releasing them back.

JavaResilience

Code

javasnippet
25 lines
import java.util.concurrent.Semaphore;

public class BulkPermitBudget {

    public static void main(String[] args) throws InterruptedException {
        Semaphore pool = new Semaphore(6, true); // fair queue for weighted jobs

        // Heavy job reserves 4 permits in a single atomic acquire(n)
        pool.acquire(4);
        System.out.println("after heavy acquire(4), available: " + pool.availablePermits());

        // Another 3-permit job cannot fit into the 2 remaining permits
        boolean fit = pool.tryAcquire(3);
        System.out.println("tryAcquire(3) succeeded: " + fit);

        // Maintenance drains all idle permits at once to pause new admissions
        int drained = pool.drainPermits();
        System.out.println("drained idle permits: " + drained + ", left: " + pool.availablePermits());

        // Heavy job releases its 4 permits, then maintenance restores the drained slots
        pool.release(4);
        pool.release(drained);
        System.out.println("restored permits: " + pool.availablePermits());
    }
}

Inside the implementation — Semaphore Bulk Permits And DrainPermits

Under the hood: the class BulkPermitBudget.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

Output lines are prefixed (after heavy acquire(4), available:, tryAcquire(3) succeeded:, drained idle permits:), ensuring terminal rows expose the outcome of individual calls.

Core lines

Semaphore pool = new Semaphore(6, true); // fair queue for weighted jobs
// Heavy job reserves 4 permits in a single atomic acquire(n)
pool.acquire(4);
int drained = pool.drainPermits();
boolean fit = pool.tryAcquire(3);

Interactive Tools for This Topic

FAQ

What does Semaphore Bulk Permits And DrainPermits print when run?
The script runs standalone; its 4 labeled outputs include `after heavy acquire(4), available:`, `tryAcquire(3) succeeded:`, `drained idle permits:`.