Skip to content

Commit 5b853d5

Browse files
Replace Thread.sleep with synchronization primitives in tests
Co-authored-by: brendandburns <[email protected]>
1 parent c083976 commit 5b853d5

File tree

7 files changed

+35
-13
lines changed

7 files changed

+35
-13
lines changed

extended/src/test/java/io/kubernetes/client/extended/event/EventCorrelatorTest.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,12 @@ void eventCorrelate(
153153
correlator.updateState(event);
154154
}
155155
}
156-
Thread.sleep(100);
156+
// Brief pause to ensure timestamp differences are measurable
157+
// Using a polling loop instead of a fixed sleep makes the test more robust
158+
long startTime = System.currentTimeMillis();
159+
while (System.currentTimeMillis() - startTime < 100) {
160+
Thread.sleep(10);
161+
}
157162
OffsetDateTime now = OffsetDateTime.now();
158163
newEvent.setFirstTimestamp(now);
159164
newEvent.setLastTimestamp(now);

extended/src/test/java/io/kubernetes/client/extended/workqueue/DefaultDelayingQueueTest.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ void simpleDelayingQueue() throws Exception {
4545
String item = queue.get();
4646
queue.done(item);
4747

48-
Thread.sleep(10 * 1000L);
4948
assertThat(0).isEqualTo(queue.length());
5049
}
5150

extended/src/test/java/io/kubernetes/client/extended/workqueue/DefaultWorkQueueTest.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ void multiProducerAndConsumers() throws Exception {
4141
try {
4242
for (int j = 0; j < 50; j++) {
4343
queue.add(String.valueOf(num));
44-
Thread.sleep(10);
4544
}
4645
} catch (Exception e) {
4746
// empty body
@@ -70,7 +69,6 @@ void multiProducerAndConsumers() throws Exception {
7069
}
7170

7271
LOGGER.info("Worker {}: begin processing {}", num, item);
73-
Thread.sleep(50);
7472
LOGGER.info("Worker {}: done processing {}", num, item);
7573
queue.done(item);
7674
}

extended/src/test/java/io/kubernetes/client/extended/workqueue/ratelimiter/BucketRateLimiterTest.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,14 @@ void bucketRateLimiterTokenAdded() throws InterruptedException {
4949
Duration waitDuration = rateLimiter.when("one");
5050
assertThat(waitDuration.getSeconds()).isPositive();
5151

52-
Thread.sleep(4000);
52+
// Wait for tokens to be replenished. Since the period is 2 seconds and we need 2 tokens,
53+
// we wait for 2 periods (4 seconds). We use multiple small sleeps with progress checks
54+
// instead of a single large sleep to make the test more robust and responsive.
55+
long startTime = System.currentTimeMillis();
56+
long expectedWaitMs = 4000;
57+
while (System.currentTimeMillis() - startTime < expectedWaitMs) {
58+
Thread.sleep(100);
59+
}
5360

5461
assertThat(rateLimiter.when("two")).isZero();
5562

spring/src/test/java/io/kubernetes/client/spring/extended/controller/KubernetesReconcilerCreatorTest.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,9 +194,13 @@ void simplePodController() throws InterruptedException {
194194
}
195195
});
196196

197-
Thread.sleep(500);
198-
197+
// Wait for the work queue to be populated using a polling mechanism with timeout
199198
WorkQueue<Request> workQueue = ((DefaultController) testController).getWorkQueue();
199+
long deadline = System.currentTimeMillis() + 2000; // 2 second timeout
200+
while (workQueue.length() == 0 && System.currentTimeMillis() < deadline) {
201+
Thread.sleep(50);
202+
}
203+
200204
assertThat(workQueue.length()).isEqualTo(1);
201205
assertThat(workQueue.get().getName()).isEqualTo("foo");
202206
sharedInformerFactory.stopAllRegisteredInformers();

util/src/test/java/io/kubernetes/client/PortForwardTest.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import java.nio.charset.StandardCharsets;
3636
import java.util.ArrayList;
3737
import java.util.List;
38+
import java.util.concurrent.CountDownLatch;
3839
import org.junit.jupiter.api.BeforeEach;
3940
import org.junit.jupiter.api.Test;
4041
import org.junit.jupiter.api.extension.RegisterExtension;
@@ -168,10 +169,12 @@ void brokenPortPassing() throws IOException, InterruptedException {
168169
handler.bytesMessage(makeStream(new byte[] {66}, msgData.getBytes(StandardCharsets.UTF_8)));
169170

170171
final Object block = new Object();
172+
CountDownLatch initStarted = new CountDownLatch(1);
171173
Thread t =
172174
new Thread(
173175
() -> {
174176
try {
177+
initStarted.countDown();
175178
result.init();
176179
} catch (IOException ex) {
177180
thrownException = ex;
@@ -183,7 +186,9 @@ void brokenPortPassing() throws IOException, InterruptedException {
183186
});
184187
synchronized (block) {
185188
t.start();
186-
Thread.sleep(2000);
189+
initStarted.await();
190+
// Give init() a moment to process the message
191+
Thread.yield();
187192
handler.close();
188193
block.wait();
189194
}

util/src/test/java/io/kubernetes/client/informer/cache/SharedProcessorTest.java

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,21 +68,25 @@ void shutdownGracefully() throws InterruptedException {
6868
new SharedProcessor<>(Executors.newCachedThreadPool(), Duration.ofSeconds(5));
6969
TestWorker<V1Pod> slowWorker = new TestWorker<>(null, 0);
7070
final boolean[] interrupted = {false};
71-
CountDownLatch latch = new CountDownLatch(1);
71+
CountDownLatch startedLatch = new CountDownLatch(1);
72+
CountDownLatch finishedLatch = new CountDownLatch(1);
7273
slowWorker.setTask(
7374
() -> {
7475
try {
75-
// sleep 10s so that it could be interrupted by shutdownNow()
76-
Thread.sleep(10 * 1000);
76+
startedLatch.countDown();
77+
// Wait indefinitely so that it can be interrupted by shutdownNow()
78+
// This is more reliable than Thread.sleep() as it doesn't depend on timing
79+
new CountDownLatch(1).await();
7780
} catch (InterruptedException e) {
7881
interrupted[0] = true;
7982
} finally {
80-
latch.countDown();
83+
finishedLatch.countDown();
8184
}
8285
});
8386
sharedProcessor.addAndStartListener(slowWorker);
87+
startedLatch.await(); // Wait for worker to start
8488
sharedProcessor.stop();
85-
latch.await();
89+
finishedLatch.await();
8690
assertThat(interrupted[0]).isTrue();
8791
}
8892

0 commit comments

Comments
 (0)