Advanced concurrency
advconcurrency5Exchanger
- Path
- pkg16advconcurrency/advconcurrency5Exchanger.java
- Package
- pkg16advconcurrency
- Study order
- 5
- Run
- Single-file source launch
- Command
- java pkg16advconcurrency/advconcurrency5Exchanger.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg16advconcurrency;2 3import java.util.concurrent.Exchanger;4import java.util.concurrent.ExecutorService;5import java.util.concurrent.Executors;6import java.util.concurrent.TimeUnit;7 8/*9 * advconcurrency5Exchanger.java10 * -----------------------------11 * Exchanger: two threads swap objects at a synchronization point.12 *13 * DEFINITION:14 * exchange(V) blocks until another thread also calls exchange, then both receive15 * the other's value. Only two parties per exchanger instance.16 *17 * KEY POINTS:18 * - Classic use: producer fills buffer, consumer takes buffer, swap empty/full.19 * - exchange(timeout) avoids indefinite wait.20 * - For N-way exchange use other structures (queues).21 */22public class advconcurrency5Exchanger {23 24 public static void main(String[] args) throws InterruptedException {25 Exchanger<String> exchanger = new Exchanger<>();26 27 try (ExecutorService pool = Executors.newFixedThreadPool(2)) {28 pool.submit(() -> {29 try {30 String received = exchanger.exchange("from-A");31 System.out.println("Thread A received: " + received);32 } catch (InterruptedException e) {33 Thread.currentThread().interrupt();34 }35 });36 pool.submit(() -> {37 try {38 Thread.sleep(100);39 String received = exchanger.exchange("from-B");40 System.out.println("Thread B received: " + received);41 } catch (InterruptedException e) {42 Thread.currentThread().interrupt();43 }44 });45 pool.shutdown();46 pool.awaitTermination(3, TimeUnit.SECONDS);47 }48 }49}