CyclicBarrier Phased Workers
Synchronize phased work with a reusable CyclicBarrier: workers await at the barrier each round and the last arrival runs the barrier action.
Code
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class PhasedCrawler {
public static void main(String[] args) throws InterruptedException {
List<String> shards = List.of("shard-a", "shard-b", "shard-c");
// 与 CountDownLatch 不同:栅栏可重复使用,每轮都重新集合
CyclicBarrier barrier = new CyclicBarrier(shards.size(),
() -> System.out.println("-- phase done, all workers synced"));
try (ExecutorService pool = Executors.newFixedThreadPool(shards.size())) {
for (String shard : shards) {
pool.submit(() -> {
try {
for (int phase = 1; phase <= 2; phase++) {
System.out.println(shard + " working phase " + phase);
// 等所有 worker 到齐再进下一轮;超时会打破栅栏
barrier.await(2, TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (BrokenBarrierException | TimeoutException e) {
System.out.println(shard + " gave up: " + e);
}
});
}
}
}
}How it works
The snippet is organized around the class PhasedCrawler.
Repetition is confined to for (String shard : shards) — the rest of the file is straight-line. try-with-resources closes each declared resource automatically on every exit path.
Using it
The demo output is labeled (-- phase done, all workers synced), so every printed line maps back to its originating operation.
Key statements
Thread.currentThread().interrupt();
Interactive Tools for This Topic
FAQ
- What does CyclicBarrier Phased Workers print when run?
- Invoke the file as-is — the `-- phase done, all workers synced` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.