Advanced concurrency

advconcurrency3Semaphore

Path
pkg16advconcurrency/advconcurrency3Semaphore.java
Package
pkg16advconcurrency
Study order
3
Run
Single-file source launch
Command
java pkg16advconcurrency/advconcurrency3Semaphore.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg16advconcurrency/advconcurrency3Semaphore.java
1package pkg16advconcurrency;2 3import java.util.concurrent.ExecutorService;4import java.util.concurrent.Executors;5import java.util.concurrent.Semaphore;6import java.util.concurrent.TimeUnit;7 8/*9 * advconcurrency3Semaphore.java10 * -----------------------------11 * Semaphore: limit concurrent access to a resource (permits).12 *13 * DEFINITION:14 *   A semaphore maintains a set of permits. acquire() takes one (blocks if none);15 *   release() returns one. Fair semaphores queue waiting threads in order.16 *17 * KEY POINTS:18 *   - Binary semaphore (1 permit) acts like a lock but can release from another thread.19 *   - Use for connection pools, rate limiting, parking slots.20 *   - Always release in finally — leaked permits starve other threads.21 */22public class advconcurrency3Semaphore {23 24    public static void main(String[] args) throws InterruptedException {25        int maxConcurrent = 2;26        Semaphore pool = new Semaphore(maxConcurrent, true); // fair27 28        try (ExecutorService exec = Executors.newFixedThreadPool(5)) {29            for (int i = 0; i < 5; i++) {30                int id = i;31                exec.submit(() -> {32                    try {33                        System.out.println("  task " + id + " waiting for permit");34                        pool.acquire();35                        System.out.println("  task " + id + " acquired permit, running");36                        Thread.sleep(200);37                    } catch (InterruptedException e) {38                        Thread.currentThread().interrupt();39                    } finally {40                        pool.release();41                        System.out.println("  task " + id + " released permit");42                    }43                });44            }45            exec.shutdown();46            exec.awaitTermination(5, TimeUnit.SECONDS);47        }48        System.out.println("Max " + maxConcurrent + " tasks ran concurrently at any time");49    }50}