From ea4d800538eb580667f3f2c4106f6d5c0a74d92c Mon Sep 17 00:00:00 2001 From: Zoltan Farkas Date: Sat, 9 Dec 2023 00:30:29 -0500 Subject: [PATCH] [fix] flaky test --- .../src/test/java/org/spf4j/net/SntpClientTest.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/spf4j-core/src/test/java/org/spf4j/net/SntpClientTest.java b/spf4j-core/src/test/java/org/spf4j/net/SntpClientTest.java index 05cebc7ab6..dd48520852 100644 --- a/spf4j-core/src/test/java/org/spf4j/net/SntpClientTest.java +++ b/spf4j-core/src/test/java/org/spf4j/net/SntpClientTest.java @@ -71,7 +71,7 @@ public void test() throws IOException, InterruptedException, TimeoutException { } @Test - public void test2() throws IOException { + public void test2() throws IOException, InterruptedException, TimeoutException { try (Closeable runUdpServer = runUdpServer(false)) { Timing timing = SntpClient.requestTime("localhost", 50123, 20); long currentTimeMachine = System.currentTimeMillis(); @@ -105,18 +105,19 @@ public void test3() { Assert.assertTrue(Math.abs(currentTimeMillis - readTimeStamp) < 2); } - public static Closeable runUdpServer(final boolean hickup) { + public static Closeable runUdpServer(final boolean hickup) throws InterruptedException, + TimeoutException, IOException { return new Closeable() { private volatile boolean terminated = false; + private final DatagramSocket socket = RetryPolicy.defaultPolicy().call( + () -> new DatagramSocket(50123), IOException.class, 2, TimeUnit.MINUTES); private Future server = org.spf4j.concurrent.DefaultExecutor.INSTANCE.submit(new AbstractRunnable(true) { @Override @SuppressFBWarnings("MDM_THREAD_YIELD") // not ideal - public void doRun() throws IOException, InterruptedException, TimeoutException { + public void doRun() throws IOException, InterruptedException { boolean first = true; - try (DatagramSocket socket = RetryPolicy.defaultPolicy().call( - () -> new DatagramSocket(50123), IOException.class, 2, TimeUnit.MINUTES)) { socket.setSoTimeout(1000); byte[] buffer = new byte[48]; DatagramPacket request = new DatagramPacket(buffer, buffer.length); @@ -142,7 +143,6 @@ public void doRun() throws IOException, InterruptedException, TimeoutException { socket.send(response); LOG.debug("Server reply to {} with {}", request.getPort(), buffer); } - } } }); @@ -150,6 +150,7 @@ public void doRun() throws IOException, InterruptedException, TimeoutException { public void close() { terminated = true; server.cancel(true); + socket.close(); } };