|
21 | 21 | import java.time.Duration; |
22 | 22 | import java.util.concurrent.CountDownLatch; |
23 | 23 | import java.util.concurrent.Executors; |
| 24 | +import java.util.concurrent.Semaphore; |
| 25 | +import java.util.concurrent.TimeUnit; |
| 26 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 27 | + |
24 | 28 | import org.junit.jupiter.api.Test; |
25 | 29 |
|
26 | 30 | class SharedProcessorTest { |
27 | 31 |
|
| 32 | + private static final long TIMEOUT_SECONDS = 10; |
| 33 | + |
28 | 34 | @Test |
29 | 35 | void listenerAddition() throws InterruptedException { |
30 | 36 |
|
@@ -67,23 +73,33 @@ void shutdownGracefully() throws InterruptedException { |
67 | 73 | SharedProcessor<V1Pod> sharedProcessor = |
68 | 74 | new SharedProcessor<>(Executors.newCachedThreadPool(), Duration.ofSeconds(5)); |
69 | 75 | TestWorker<V1Pod> slowWorker = new TestWorker<>(null, 0); |
70 | | - final boolean[] interrupted = {false}; |
71 | | - CountDownLatch latch = new CountDownLatch(1); |
| 76 | + AtomicBoolean interrupted = new AtomicBoolean(); |
| 77 | + Semaphore workerStarted = new Semaphore(0); |
| 78 | + Semaphore blockWorker = new Semaphore(0); |
| 79 | + Semaphore workerFinished = new Semaphore(0); |
72 | 80 | slowWorker.setTask( |
73 | 81 | () -> { |
| 82 | + workerStarted.release(); |
74 | 83 | try { |
75 | | - // sleep 10s so that it could be interrupted by shutdownNow() |
76 | | - Thread.sleep(10 * 1000); |
| 84 | + blockWorker.acquire(); |
77 | 85 | } catch (InterruptedException e) { |
78 | | - interrupted[0] = true; |
| 86 | + interrupted.set(true); |
| 87 | + Thread.currentThread().interrupt(); |
79 | 88 | } finally { |
80 | | - latch.countDown(); |
| 89 | + workerFinished.release(); |
81 | 90 | } |
82 | 91 | }); |
83 | 92 | sharedProcessor.addAndStartListener(slowWorker); |
84 | | - sharedProcessor.stop(); |
85 | | - latch.await(); |
86 | | - assertThat(interrupted[0]).isTrue(); |
| 93 | + boolean started = workerStarted.tryAcquire(TIMEOUT_SECONDS, TimeUnit.SECONDS); |
| 94 | + try { |
| 95 | + assertThat(started).as("worker started").isTrue(); |
| 96 | + } finally { |
| 97 | + sharedProcessor.stop(); |
| 98 | + } |
| 99 | + assertThat(workerFinished.tryAcquire(TIMEOUT_SECONDS, TimeUnit.SECONDS)) |
| 100 | + .as("worker finished") |
| 101 | + .isTrue(); |
| 102 | + assertThat(interrupted.get()).as("worker was interrupted").isTrue(); |
87 | 103 | } |
88 | 104 |
|
89 | 105 | private static class ExpectingNoticationHandler<ApiType extends KubernetesObject> |
|
0 commit comments