1+ package com .baeldung .concurrent .countdownlatch ;
2+
3+ import org .assertj .core .api .Assertions ;
4+ import org .junit .Test ;
5+
6+ import java .util .ArrayList ;
7+ import java .util .Collections ;
8+ import java .util .List ;
9+ import java .util .concurrent .CountDownLatch ;
10+ import java .util .concurrent .TimeUnit ;
11+ import java .util .concurrent .TimeoutException ;
12+ import java .util .stream .Stream ;
13+
14+ import static java .util .stream .Collectors .toList ;
15+ import static org .assertj .core .api .Assertions .assertThat ;
16+
17+ public class CountdownLatchExampleTest {
18+ @ Test
19+ public void shouldBlockUntilLatchIsReleased () throws InterruptedException {
20+
21+ // Given
22+ List <String > outputScraper = Collections .synchronizedList (new ArrayList <>());
23+ CountDownLatch countDownLatch = new CountDownLatch (5 );
24+ List <Thread > workers = Stream
25+ .generate (() -> new Thread (new Worker (outputScraper , countDownLatch )))
26+ .limit (5 )
27+ .collect (toList ());
28+
29+ // When
30+ workers .forEach (Thread ::start );
31+ countDownLatch .await (); // Block until workers finish
32+ outputScraper .add ("Latch released" );
33+
34+ // Then
35+ outputScraper .forEach (Object ::toString );
36+ assertThat (outputScraper )
37+ .containsExactly (
38+ "Counted down" ,
39+ "Counted down" ,
40+ "Counted down" ,
41+ "Counted down" ,
42+ "Counted down" ,
43+ "Latch released"
44+ );
45+ }
46+
47+ @ Test
48+ public void shouldEventuallyTimeout () throws InterruptedException {
49+ // Given
50+ List <String > outputScraper = Collections .synchronizedList (new ArrayList <>());
51+ CountDownLatch countDownLatch = new CountDownLatch (5 );
52+ List <Thread > workers = Stream
53+ .generate (() -> new Thread (new BrokenWorker (outputScraper , countDownLatch )))
54+ .limit (5 )
55+ .collect (toList ());
56+
57+ // When
58+ workers .forEach (Thread ::start );
59+ final boolean result = countDownLatch .await (3L , TimeUnit .SECONDS );
60+
61+ // Then
62+ assertThat (result ).isTrue ();
63+ }
64+ }
0 commit comments