Concurrency
concurrency8LocksAndCoordination
- Path
- pkg7concurrency/concurrency8LocksAndCoordination.java
- Package
- pkg7concurrency
- Study order
- 8
- Run
- Single-file source launch
- Command
- java pkg7concurrency/concurrency8LocksAndCoordination.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg7concurrency;2 3/*4 * concurrency8LocksAndCoordination.java5 * -------------------------6 * java.util.concurrent coordination tools: ReentrantLock, ReadWriteLock,7 * CountDownLatch, Semaphore, and a deadlock-avoidance note.8 */9import java.util.concurrent.*;10import java.util.concurrent.locks.*;11import java.util.concurrent.atomic.AtomicInteger;12 13public class concurrency8LocksAndCoordination {14 15 public static void main(String[] args) throws InterruptedException {16 countDownLatchDemo();17 readWriteLockDemo();18 semaphoreDemo();19 }20 21 // CountDownLatch: wait for N tasks to complete before proceeding.22 static void countDownLatchDemo() throws InterruptedException {23 int workers = 4;24 CountDownLatch latch = new CountDownLatch(workers);25 for (int i = 0; i < workers; i++) {26 int id = i;27 new Thread(() -> {28 try { Thread.sleep(20 * id); } catch (InterruptedException ignored) {}29 latch.countDown(); // signal completion30 }).start();31 }32 latch.await(); // block until count reaches 033 System.out.println("[CountDownLatch] all " + workers + " workers finished");34 }35 36 // ReadWriteLock: many readers OR one writer (improves read-heavy throughput).37 static void readWriteLockDemo() throws InterruptedException {38 ReadWriteLock rw = new ReentrantReadWriteLock();39 AtomicInteger shared = new AtomicInteger(0);40 41 Runnable writer = () -> {42 rw.writeLock().lock();43 try { shared.incrementAndGet(); } finally { rw.writeLock().unlock(); }44 };45 Runnable reader = () -> {46 rw.readLock().lock();47 try { shared.get(); } finally { rw.readLock().unlock(); }48 };49 50 Thread[] ts = new Thread[6];51 for (int i = 0; i < ts.length; i++) ts[i] = new Thread(i % 2 == 0 ? reader : writer);52 for (Thread t : ts) t.start();53 for (Thread t : ts) t.join();54 System.out.println("[ReadWriteLock] writes applied, shared = " + shared.get());55 }56 57 // Semaphore: limit concurrent access to a resource (e.g. a connection pool).58 static void semaphoreDemo() throws InterruptedException {59 Semaphore permits = new Semaphore(2); // only 2 at a time60 AtomicInteger maxConcurrent = new AtomicInteger();61 AtomicInteger current = new AtomicInteger();62 63 Thread[] ts = new Thread[6];64 for (int i = 0; i < ts.length; i++) {65 ts[i] = new Thread(() -> {66 try {67 permits.acquire();68 int now = current.incrementAndGet();69 maxConcurrent.accumulateAndGet(now, Math::max);70 Thread.sleep(20);71 current.decrementAndGet();72 permits.release();73 } catch (InterruptedException ignored) {}74 });75 }76 for (Thread t : ts) t.start();77 for (Thread t : ts) t.join();78 System.out.println("[Semaphore] max concurrent observed = " + maxConcurrent.get() + " (cap = 2)");79 }80}