Skip to content

Commit 18b6645

Browse files
authored
BAEL-3439 - Add selector.wakeup() section (eugenp#10398)
* Add selector.wakeup() section * Update SelectorTest.java * Update core-java-modules/core-java-nio-2/src/test/java/com/baeldung/selector/SelectorTest.java * Update SelectorTest.java * Update and rename SelectorTest.java to SelectorUnitTest.java * Update SelectorUnitTest.java * Update and rename SelectorUnitTest.java to SelectorManualTest.java
1 parent 93ec34b commit 18b6645

2 files changed

Lines changed: 72 additions & 1 deletion

File tree

core-java-modules/core-java-nio-2/pom.xml

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,12 @@
1414
<version>0.0.1-SNAPSHOT</version>
1515
<relativePath>../</relativePath>
1616
</parent>
17-
17+
<dependencies>
18+
<dependency>
19+
<groupId>org.assertj</groupId>
20+
<artifactId>assertj-core</artifactId>
21+
<version>3.6.1</version>
22+
<scope>test</scope>
23+
</dependency>
24+
</dependencies>
1825
</project>
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.selector;
2+
3+
import org.junit.Test;
4+
import java.io.IOException;
5+
import java.nio.channels.Pipe;
6+
import java.nio.channels.SelectableChannel;
7+
import java.nio.channels.Selector;
8+
import java.util.ArrayList;
9+
import java.util.Collections;
10+
import java.util.List;
11+
import java.util.concurrent.CountDownLatch;
12+
13+
import static org.assertj.core.api.Assertions.assertThat;
14+
15+
import static java.nio.channels.SelectionKey.OP_READ;
16+
17+
public class SelectorManualTest {
18+
19+
@Test
20+
public void whenWakeUpCalledOnSelector_thenBlockedThreadReturns() throws IOException, InterruptedException {
21+
Pipe pipe = Pipe.open();
22+
23+
Selector selector = Selector.open();
24+
SelectableChannel channel = pipe.source();
25+
channel.configureBlocking(false);
26+
channel.register(selector, OP_READ);
27+
28+
List<String> invocationStepsTracker = Collections.synchronizedList(new ArrayList<>());
29+
30+
CountDownLatch latch = new CountDownLatch(1);
31+
32+
Thread thread = new Thread(() -> {
33+
invocationStepsTracker.add(">> Count down");
34+
latch.countDown();
35+
try {
36+
invocationStepsTracker.add(">> Start select");
37+
selector.select();
38+
invocationStepsTracker.add(">> End select");
39+
} catch (IOException e) {
40+
e.printStackTrace();
41+
}
42+
});
43+
44+
invocationStepsTracker.add(">> Start await");
45+
thread.start();
46+
latch.await();
47+
invocationStepsTracker.add(">> End await");
48+
49+
invocationStepsTracker.add(">> Wakeup thread");
50+
51+
selector.wakeup();
52+
channel.close();
53+
54+
assertThat(invocationStepsTracker)
55+
.containsExactly(
56+
">> Start await",
57+
">> Count down",
58+
">> Start select",
59+
">> End await",
60+
">> Wakeup thread",
61+
">> End select"
62+
);
63+
}
64+
}

0 commit comments

Comments
 (0)