Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use synchronization classes instead of Thread.sleep in test cases #2626

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,19 @@
*/
package io.kubernetes.client.informer.cache;

import static org.junit.Assert.*;

import io.kubernetes.client.common.KubernetesObject;
import io.kubernetes.client.informer.ResourceEventHandler;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Pod;
import org.junit.Test;

import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import org.junit.Test;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.assertTrue;

public class SharedProcessorTest {

Expand Down Expand Up @@ -65,25 +68,21 @@ public void testListenerAddition() throws InterruptedException {
@Test
public void testShutdownGracefully() throws InterruptedException {
SharedProcessor<V1Pod> sharedProcessor =
new SharedProcessor<>(Executors.newCachedThreadPool(), Duration.ofSeconds(5));
new SharedProcessor<>(Executors.newCachedThreadPool(), Duration.ofSeconds(5));
TestWorker<V1Pod> slowWorker = new TestWorker<>(null, 0);
final boolean[] interrupted = {false};
CountDownLatch latch = new CountDownLatch(1);
slowWorker.setTask(
() -> {
try {
// sleep 10s so that it could be interrupted by shutdownNow()
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
interrupted[0] = true;
} finally {
latch.countDown();
}
});
AtomicBoolean wasInterrupted = new AtomicBoolean(false);
Semaphore semaphore = new Semaphore(0);
slowWorker.setTask(() -> {
try {
semaphore.acquire(); // wait for stop() to be called
} catch (InterruptedException e) {
wasInterrupted.set(true);
}
});
sharedProcessor.addAndStartListener(slowWorker);
sharedProcessor.stop();
latch.await();
assertTrue(interrupted[0]);
semaphore.release(); // allow worker to finish
assertTrue(wasInterrupted.get());
}

private static class ExpectingNoticationHandler<ApiType extends KubernetesObject>
Expand Down