Skip to content

Commit 6ba9ab7

Browse files
committed
Add synchronization to ensure that server starts before client connects.
1 parent 2048099 commit 6ba9ab7

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

utils/socket-utils/src/test/java/datadog/common/socket/TunnelingJdkSocketTest.java

+22-8
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616

1717
public class TunnelingJdkSocketTest {
1818

19-
private static final AtomicBoolean is_server_running = new AtomicBoolean(false);
20-
private final int client_timeout = 1000;
21-
private final int test_timeout = 3000;
19+
private static final AtomicBoolean isServerRunning = new AtomicBoolean(false);
20+
private final int clientTimeout = 1000;
21+
private final int testTimeout = 3000;
2222

2323
@Test
2424
public void testTimeout() throws Exception {
@@ -28,10 +28,10 @@ public void testTimeout() throws Exception {
2828
TunnelingJdkSocket clientSocket = createClient(socketPath);
2929

3030
assertTimeoutPreemptively(
31-
Duration.ofMillis(test_timeout), () -> clientSocket.getInputStream().read());
31+
Duration.ofMillis(testTimeout), () -> clientSocket.getInputStream().read());
3232

3333
clientSocket.close();
34-
is_server_running.set(false);
34+
isServerRunning.set(false);
3535
}
3636

3737
private Path getSocketPath() throws IOException {
@@ -48,22 +48,36 @@ private static void startServer(UnixDomainSocketAddress socketAddress) {
4848
try (ServerSocketChannel serverChannel =
4949
ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
5050
serverChannel.bind(socketAddress);
51-
is_server_running.set(true);
51+
isServerRunning.set(true);
5252

53-
while (is_server_running.get()) {
53+
synchronized (isServerRunning) {
54+
isServerRunning.notifyAll();
55+
}
56+
57+
while (isServerRunning.get()) {
5458
SocketChannel clientChannel = serverChannel.accept();
5559
}
5660
} catch (IOException e) {
5761
throw new RuntimeException(e);
5862
}
5963
});
6064
serverThread.start();
65+
66+
synchronized (isServerRunning) {
67+
while (!isServerRunning.get()) {
68+
try {
69+
isServerRunning.wait();
70+
} catch (InterruptedException e) {
71+
throw new RuntimeException(e);
72+
}
73+
}
74+
}
6175
}
6276

6377
private TunnelingJdkSocket createClient(Path socketPath) throws IOException {
6478
TunnelingJdkSocket clientSocket = new TunnelingJdkSocket(socketPath);
6579
clientSocket.connect(new InetSocketAddress("localhost", 0));
66-
clientSocket.setSoTimeout(client_timeout);
80+
clientSocket.setSoTimeout(clientTimeout);
6781
return clientSocket;
6882
}
6983
}

0 commit comments

Comments
 (0)