1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.lang3.concurrent;
18
19 import static org.apache.commons.lang3.LangAssertions.assertIllegalArgumentException;
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertFalse;
22 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
23 import static org.junit.jupiter.api.Assertions.assertNotNull;
24 import static org.junit.jupiter.api.Assertions.assertNull;
25 import static org.junit.jupiter.api.Assertions.assertThrows;
26 import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
27 import static org.junit.jupiter.api.Assertions.assertTrue;
28
29 import java.time.Duration;
30 import java.util.concurrent.BlockingQueue;
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.FutureTask;
33 import java.util.concurrent.LinkedBlockingQueue;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.ScheduledFuture;
36 import java.util.concurrent.ScheduledThreadPoolExecutor;
37 import java.util.concurrent.TimeUnit;
38
39 import org.apache.commons.lang3.AbstractLangTest;
40 import org.apache.commons.lang3.ThreadUtils;
41 import org.easymock.EasyMock;
42 import org.junit.jupiter.api.Test;
43
44
45
46
47 class TimedSemaphoreTest extends AbstractLangTest {
48
49 private static final class EqualFairAcquirer extends FairAcquirer {
50 EqualFairAcquirer(final TimedSemaphore semaphore, final BlockingQueue<Integer> order, final int id) {
51 super(semaphore, order, id);
52 }
53
54 @Override
55 public boolean equals(final Object other) {
56 return other instanceof EqualFairAcquirer;
57 }
58
59 @Override
60 public int hashCode() {
61 return 1;
62 }
63 }
64
65 private static class FairAcquirer extends Thread {
66 private final TimedSemaphore semaphore;
67 private final BlockingQueue<Integer> order;
68 private final int id;
69 private volatile Exception failure;
70
71 FairAcquirer(final TimedSemaphore semaphore, final BlockingQueue<Integer> order, final int id) {
72 this.semaphore = semaphore;
73 this.order = order;
74 this.id = id;
75 setDaemon(true);
76 }
77
78 @Override
79 public void run() {
80 try {
81 semaphore.acquire();
82 order.add(id);
83 } catch (final InterruptedException | IllegalStateException ex) {
84 failure = ex;
85 }
86 }
87 }
88
89
90
91
92
93
94 private static final class SemaphoreThread extends Thread {
95
96
97 private final TimedSemaphore semaphore;
98
99
100 private final CountDownLatch latch;
101
102
103 private final int count;
104
105
106 private final int latchCount;
107
108 SemaphoreThread(final TimedSemaphore b, final CountDownLatch l, final int c, final int lc) {
109 semaphore = b;
110 latch = l;
111 count = c;
112 latchCount = lc;
113 }
114
115
116
117
118
119
120 @Override
121 public void run() {
122 try {
123 for (int i = 0; i < count; i++) {
124 semaphore.acquire();
125
126 if (i < latchCount) {
127 latch.countDown();
128 }
129 }
130 } catch (final InterruptedException iex) {
131 Thread.currentThread().interrupt();
132 }
133 }
134 }
135
136
137
138
139
140 private static final class TimedSemaphoreTestImpl extends TimedSemaphore {
141
142
143 ScheduledFuture<?> schedFuture;
144
145
146 volatile CountDownLatch latch;
147
148
149 private int periodEnds;
150
151 TimedSemaphoreTestImpl(final long timePeriod, final TimeUnit timeUnit, final int limit) {
152 super(timePeriod, timeUnit, limit);
153 }
154
155 TimedSemaphoreTestImpl(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit) {
156 super(service, timePeriod, timeUnit, limit);
157 }
158
159
160
161
162
163
164 @Override
165 public synchronized void acquire() throws InterruptedException {
166 super.acquire();
167 if (latch != null) {
168 latch.countDown();
169 }
170 }
171
172
173
174
175 @Override
176 protected synchronized void endOfPeriod() {
177 super.endOfPeriod();
178 periodEnds++;
179 }
180
181
182
183
184
185
186 int getPeriodEnds() {
187 synchronized (this) {
188 return periodEnds;
189 }
190 }
191
192
193
194
195 @Override
196 protected ScheduledFuture<?> startTimer() {
197 return schedFuture != null ? schedFuture : super.startTimer();
198 }
199 }
200
201
202
203
204
205 private static final class TryAcquireThread extends Thread {
206
207
208 private final TimedSemaphore semaphore;
209
210
211 private final CountDownLatch latch;
212
213
214 private boolean acquired;
215
216 TryAcquireThread(final TimedSemaphore s, final CountDownLatch l) {
217 semaphore = s;
218 latch = l;
219 }
220
221 @Override
222 public void run() {
223 try {
224 if (latch.await(10, TimeUnit.SECONDS)) {
225 acquired = semaphore.tryAcquire();
226 }
227 } catch (final InterruptedException iex) {
228
229 }
230 }
231 }
232
233
234 private static final long PERIOD_MILLIS = 500;
235
236 private static final Duration DURATION = Duration.ofMillis(PERIOD_MILLIS);
237
238
239 private static final TimeUnit UNIT = TimeUnit.MILLISECONDS;
240
241
242 private static final int LIMIT = 10;
243
244 private static void assertAcquireOrder(final TimedSemaphore semaphore, final boolean fair) throws Exception {
245 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
246 final FairAcquirer first = new FairAcquirer(semaphore, order, 1);
247 final FutureTask<Void> newcomerTask = new FutureTask<>(() -> {
248 synchronized (semaphore) {
249 semaphore.endOfPeriod();
250
251 semaphore.acquire();
252 order.add(2);
253 }
254 return null;
255 });
256 final Thread newcomer = new Thread(newcomerTask);
257 newcomer.setDaemon(true);
258 try {
259 semaphore.acquire();
260 first.start();
261 awaitWaiting(first);
262 newcomer.start();
263 assertEquals(Integer.valueOf(fair ? 1 : 2), order.poll(5, TimeUnit.SECONDS));
264 assertEquals(1, semaphore.getAcquireCount());
265 semaphore.endOfPeriod();
266 newcomerTask.get(5, TimeUnit.SECONDS);
267 assertEquals(Integer.valueOf(fair ? 2 : 1), order.poll(5, TimeUnit.SECONDS));
268 assertNull(first.failure);
269 } finally {
270 newcomer.interrupt();
271 try {
272 stopAcquirers(semaphore, first);
273 } finally {
274 newcomer.join(5000);
275 assertFalse(newcomer.isAlive());
276 }
277 }
278 }
279
280 private static void awaitWaiting(final Thread thread) throws InterruptedException {
281 final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
282 while (thread.getState() != Thread.State.WAITING && thread.isAlive() && System.nanoTime() < deadline) {
283 Thread.sleep(1);
284 }
285 assertEquals(Thread.State.WAITING, thread.getState(), "Caller must be queued before the test proceeds");
286 }
287
288 private static TimedSemaphore newFairSemaphore(final int limit) {
289 return TimedSemaphore.builder().setPeriod(1).setTimeUnit(TimeUnit.DAYS).setLimit(limit).setFair(true).get();
290 }
291
292 private static void stopAcquirers(final TimedSemaphore semaphore, final FairAcquirer... threads) throws InterruptedException {
293 semaphore.shutdown();
294 for (final FairAcquirer thread : threads) {
295 thread.interrupt();
296 thread.join(5000);
297 assertFalse(thread.isAlive(), "Acquirer did not terminate");
298 }
299 }
300
301
302
303
304
305
306
307 private void prepareStartTimer(final ScheduledExecutorService service,
308 final ScheduledFuture<?> future) {
309 service.scheduleAtFixedRate((Runnable) EasyMock.anyObject(), EasyMock.eq(PERIOD_MILLIS), EasyMock.eq(PERIOD_MILLIS), EasyMock.eq(UNIT));
310 EasyMock.expectLastCall().andReturn(future);
311 }
312
313
314
315
316
317
318 @Test
319 void testAcquireLimit() throws InterruptedException {
320 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
321 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
322 prepareStartTimer(service, future);
323 EasyMock.replay(service, future);
324 final int count = 10;
325 final CountDownLatch latch = new CountDownLatch(count - 1);
326 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD_MILLIS, UNIT, 1);
327 final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count - 1);
328 semaphore.setLimit(count - 1);
329
330 t.start();
331 latch.await();
332
333 assertEquals(count - 1, semaphore.getAcquireCount(), "Wrong semaphore count");
334
335 semaphore.endOfPeriod();
336 t.join();
337 assertEquals(1, semaphore.getAcquireCount(), "Wrong semaphore count (2)");
338 assertEquals(count - 1, semaphore.getLastAcquiresPerPeriod(), "Wrong acquire() count");
339 EasyMock.verify(service, future);
340 }
341
342
343
344
345
346
347
348
349
350 @Test
351 void testAcquireMultiplePeriods() throws InterruptedException {
352 final int count = 1000;
353 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD_MILLIS / 10, TimeUnit.MILLISECONDS, 1);
354 semaphore.setLimit(count / 4);
355 final CountDownLatch latch = new CountDownLatch(count);
356 final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
357 t.start();
358 latch.await();
359 semaphore.shutdown();
360 assertTrue(semaphore.getPeriodEnds() > 0, "End of period not reached");
361 }
362
363
364
365
366
367
368
369
370
371 @Test
372 void testAcquireMultipleThreads() throws InterruptedException {
373 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
374 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
375 prepareStartTimer(service, future);
376 EasyMock.replay(service, future);
377 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD_MILLIS, UNIT, 1);
378 semaphore.latch = new CountDownLatch(1);
379 final int count = 10;
380 final SemaphoreThread[] threads = new SemaphoreThread[count];
381 for (int i = 0; i < count; i++) {
382 threads[i] = new SemaphoreThread(semaphore, null, 1, 0);
383 threads[i].start();
384 }
385 for (int i = 0; i < count; i++) {
386 semaphore.latch.await();
387 assertEquals(1, semaphore.getAcquireCount(), "Wrong count");
388 semaphore.latch = new CountDownLatch(1);
389 semaphore.endOfPeriod();
390 assertEquals(1, semaphore.getLastAcquiresPerPeriod(), "Wrong acquire count");
391 }
392 for (int i = 0; i < count; i++) {
393 threads[i].join();
394 }
395 EasyMock.verify(service, future);
396 }
397
398
399
400
401
402
403
404
405 @Test
406 void testAcquireNoLimit() throws InterruptedException {
407 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
408 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
409 prepareStartTimer(service, future);
410 EasyMock.replay(service, future);
411 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD_MILLIS, UNIT, TimedSemaphore.NO_LIMIT);
412 final int count = 1000;
413 final CountDownLatch latch = new CountDownLatch(count);
414 final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
415 t.start();
416 latch.await();
417 EasyMock.verify(service, future);
418 }
419
420 @Test
421 void testBuilderReusePreservesFairness() throws Exception {
422 final TimedSemaphore.Builder builder = TimedSemaphore.builder().setPeriod(1).setTimeUnit(TimeUnit.DAYS).setLimit(1).setFair(true);
423 final TimedSemaphore fairSemaphore = builder.get();
424 final TimedSemaphore nonFairSemaphore = builder.setFair(false).get();
425 try {
426
427 assertAcquireOrder(fairSemaphore, true);
428 builder.setFair(true);
429 assertAcquireOrder(nonFairSemaphore, false);
430 } finally {
431 fairSemaphore.shutdown();
432 nonFairSemaphore.shutdown();
433 }
434 }
435
436 @Test
437 void testFairAcquireDisabledLimitDoesNotQueueNewCallers() throws InterruptedException {
438 final TimedSemaphore semaphore = newFairSemaphore(1);
439 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
440 final FairAcquirer waiting = new FairAcquirer(semaphore, order, 1);
441 final FairAcquirer newcomer = new FairAcquirer(semaphore, order, 2);
442 try {
443 semaphore.acquire();
444 waiting.start();
445 awaitWaiting(waiting);
446 semaphore.setLimit(0);
447 newcomer.start();
448 newcomer.join(5000);
449 assertFalse(newcomer.isAlive(), "Unlimited acquisitions must not wait for the next period");
450 assertNull(newcomer.failure);
451 assertTrue(order.contains(2));
452 } finally {
453 stopAcquirers(semaphore, waiting, newcomer);
454 }
455 }
456
457 @Test
458 void testFairAcquireDisablingLimitReleasesWaitersAtRollover() throws InterruptedException {
459 final TimedSemaphore semaphore = newFairSemaphore(1);
460 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
461 final FairAcquirer first = new FairAcquirer(semaphore, order, 1);
462 final FairAcquirer second = new FairAcquirer(semaphore, order, 2);
463 try {
464 semaphore.acquire();
465 first.start();
466 awaitWaiting(first);
467 second.start();
468 awaitWaiting(second);
469 semaphore.setLimit(0);
470 semaphore.endOfPeriod();
471 assertNotNull(order.poll(5, TimeUnit.SECONDS));
472 assertNotNull(order.poll(5, TimeUnit.SECONDS));
473 assertNull(first.failure);
474 assertNull(second.failure);
475 assertEquals(2, semaphore.getAcquireCount());
476 } finally {
477 stopAcquirers(semaphore, first, second);
478 }
479 }
480
481 @Test
482 void testFairAcquireInterruptedHeadReleasesNextWaiter() throws InterruptedException {
483 final TimedSemaphore semaphore = newFairSemaphore(1);
484 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
485 final FairAcquirer first = new FairAcquirer(semaphore, order, 1);
486 final FairAcquirer second = new FairAcquirer(semaphore, order, 2);
487 try {
488 semaphore.acquire();
489 first.start();
490 awaitWaiting(first);
491 second.start();
492 awaitWaiting(second);
493 synchronized (semaphore) {
494 semaphore.setLimit(2);
495 first.interrupt();
496 }
497 first.join(5000);
498 assertFalse(first.isAlive());
499 assertInstanceOf(InterruptedException.class, first.failure);
500 assertEquals(Integer.valueOf(2), order.poll(5, TimeUnit.SECONDS));
501 assertNull(second.failure);
502 assertEquals(2, semaphore.getAcquireCount());
503 } finally {
504 stopAcquirers(semaphore, first, second);
505 }
506 }
507
508 @Test
509 void testFairAcquireInterruptedMiddlePreservesQueue() throws InterruptedException {
510 final TimedSemaphore semaphore = newFairSemaphore(1);
511 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
512
513 final FairAcquirer first = new EqualFairAcquirer(semaphore, order, 1);
514 final FairAcquirer second = new EqualFairAcquirer(semaphore, order, 2);
515 final FairAcquirer third = new EqualFairAcquirer(semaphore, order, 3);
516 try {
517 semaphore.acquire();
518 first.start();
519 awaitWaiting(first);
520 second.start();
521 awaitWaiting(second);
522 third.start();
523 awaitWaiting(third);
524 second.interrupt();
525 second.join(5000);
526 assertFalse(second.isAlive());
527 assertInstanceOf(InterruptedException.class, second.failure);
528 semaphore.endOfPeriod();
529 assertEquals(Integer.valueOf(1), order.poll(5, TimeUnit.SECONDS));
530 semaphore.endOfPeriod();
531 assertEquals(Integer.valueOf(3), order.poll(5, TimeUnit.SECONDS));
532 assertNull(first.failure);
533 assertNull(third.failure);
534 assertEquals(1, semaphore.getAcquireCount());
535 } finally {
536 stopAcquirers(semaphore, first, second, third);
537 }
538 }
539
540 @Test
541 void testFairAcquireNewcomerCannotBypassQueuedCaller() throws Exception {
542 assertAcquireOrder(newFairSemaphore(1), true);
543 }
544
545 @Test
546 void testFairAcquireOrderAcrossPeriods() throws InterruptedException {
547 final TimedSemaphore semaphore = newFairSemaphore(1);
548 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
549 final FairAcquirer first = new FairAcquirer(semaphore, order, 1);
550 final FairAcquirer second = new FairAcquirer(semaphore, order, 2);
551 final FairAcquirer third = new FairAcquirer(semaphore, order, 3);
552 try {
553 semaphore.acquire();
554 first.start();
555 awaitWaiting(first);
556 second.start();
557 awaitWaiting(second);
558 third.start();
559 awaitWaiting(third);
560 for (int expected = 1; expected <= 3; expected++) {
561 semaphore.endOfPeriod();
562 assertEquals(Integer.valueOf(expected), order.poll(5, TimeUnit.SECONDS));
563 assertEquals(1, semaphore.getAcquireCount());
564 assertEquals(0, semaphore.getAvailablePermits());
565 }
566 assertNull(first.failure);
567 assertNull(second.failure);
568 assertNull(third.failure);
569 } finally {
570 stopAcquirers(semaphore, first, second, third);
571 }
572 }
573
574 @Test
575 void testFairAcquireReleasesMultipleWaiters() throws InterruptedException {
576 final TimedSemaphore semaphore = newFairSemaphore(1);
577 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
578 final FairAcquirer first = new FairAcquirer(semaphore, order, 1);
579 final FairAcquirer second = new FairAcquirer(semaphore, order, 2);
580 try {
581 semaphore.acquire();
582 first.start();
583 awaitWaiting(first);
584 second.start();
585 awaitWaiting(second);
586 semaphore.setLimit(2);
587 semaphore.endOfPeriod();
588 assertNotNull(order.poll(5, TimeUnit.SECONDS));
589 assertNotNull(order.poll(5, TimeUnit.SECONDS));
590 assertEquals(2, semaphore.getAcquireCount());
591 assertNull(first.failure);
592 assertNull(second.failure);
593 } finally {
594 stopAcquirers(semaphore, first, second);
595 }
596 }
597
598 @Test
599 void testFairAcquireShutdownReleasesWaiters() throws InterruptedException {
600 final TimedSemaphore semaphore = newFairSemaphore(1);
601 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
602 final FairAcquirer first = new FairAcquirer(semaphore, order, 1);
603 final FairAcquirer second = new FairAcquirer(semaphore, order, 2);
604 try {
605 semaphore.acquire();
606 first.start();
607 awaitWaiting(first);
608 second.start();
609 awaitWaiting(second);
610 semaphore.shutdown();
611 first.join(5000);
612 second.join(5000);
613 assertFalse(first.isAlive());
614 assertFalse(second.isAlive());
615 assertInstanceOf(IllegalStateException.class, first.failure);
616 assertInstanceOf(IllegalStateException.class, second.failure);
617 assertTrue(order.isEmpty());
618 } finally {
619 stopAcquirers(semaphore, first, second);
620 }
621 }
622
623 @Test
624 void testFairLimitChangesPreserveAccounting() throws InterruptedException {
625 final TimedSemaphore semaphore = newFairSemaphore(3);
626 try {
627 semaphore.acquire();
628 assertTrue(semaphore.tryAcquire());
629 semaphore.setLimit(1);
630 assertFalse(semaphore.tryAcquire());
631 semaphore.setLimit(3);
632 assertEquals(1, semaphore.getAvailablePermits());
633 assertTrue(semaphore.tryAcquire());
634 semaphore.setLimit(3);
635 assertFalse(semaphore.tryAcquire());
636 semaphore.endOfPeriod();
637 assertEquals(3, semaphore.getLastAcquiresPerPeriod());
638 assertEquals(3, semaphore.getAvailablePermits());
639 assertEquals(0, semaphore.getAcquireCount());
640 semaphore.setLimit(-1);
641 for (int i = 0; i < 10; i++) {
642 semaphore.acquire();
643 }
644 assertEquals(10, semaphore.getAcquireCount());
645 } finally {
646 semaphore.shutdown();
647 }
648 }
649
650 @Test
651 void testFairTryAcquireCanBypassWaitersWithoutClearingInterrupt() throws InterruptedException {
652 final TimedSemaphore semaphore = newFairSemaphore(1);
653 final BlockingQueue<Integer> order = new LinkedBlockingQueue<>();
654 final FairAcquirer waiter = new FairAcquirer(semaphore, order, 1);
655 try {
656 semaphore.acquire();
657 waiter.start();
658 awaitWaiting(waiter);
659 synchronized (semaphore) {
660 semaphore.endOfPeriod();
661 Thread.currentThread().interrupt();
662 try {
663 assertTrue(semaphore.tryAcquire());
664 assertTrue(Thread.currentThread().isInterrupted());
665 assertFalse(semaphore.tryAcquire());
666 } finally {
667 Thread.interrupted();
668 }
669 }
670 semaphore.endOfPeriod();
671 assertEquals(Integer.valueOf(1), order.poll(5, TimeUnit.SECONDS));
672 assertNull(waiter.failure);
673 } finally {
674 stopAcquirers(semaphore, waiter);
675 }
676 }
677
678
679
680
681
682
683 @Test
684 void testGetAvailablePermits() throws InterruptedException {
685 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
686 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
687 prepareStartTimer(service, future);
688 EasyMock.replay(service, future);
689 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD_MILLIS, UNIT, LIMIT);
690 for (int i = 0; i < LIMIT; i++) {
691 assertEquals(LIMIT - i, semaphore.getAvailablePermits(), "Wrong available count at " + i);
692 semaphore.acquire();
693 }
694 semaphore.endOfPeriod();
695 assertEquals(LIMIT, semaphore.getAvailablePermits(), "Wrong available count in new period");
696 EasyMock.verify(service, future);
697 }
698
699
700
701
702
703
704 @Test
705 void testGetAverageCallsPerPeriod() throws InterruptedException {
706 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
707 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
708 prepareStartTimer(service, future);
709 EasyMock.replay(service, future);
710 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD_MILLIS, UNIT, LIMIT);
711 semaphore.acquire();
712 semaphore.endOfPeriod();
713 assertEquals(1.0, semaphore.getAverageCallsPerPeriod(), .005, "Wrong average (1)");
714 semaphore.acquire();
715 semaphore.acquire();
716 semaphore.endOfPeriod();
717 assertEquals(1.5, semaphore.getAverageCallsPerPeriod(), .005, "Wrong average (2)");
718 EasyMock.verify(service, future);
719 }
720
721
722
723
724 @Test
725 void testInit() {
726 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
727 EasyMock.replay(service);
728 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD_MILLIS, UNIT, LIMIT);
729 EasyMock.verify(service);
730 assertEquals(service, semaphore.getExecutorService(), "Wrong service");
731 assertEquals(PERIOD_MILLIS, semaphore.getPeriod(), "Wrong period");
732 assertEquals(UNIT, semaphore.getUnit(), "Wrong unit");
733 assertEquals(0, semaphore.getLastAcquiresPerPeriod(), "Statistic available");
734 assertEquals(0.0, semaphore.getAverageCallsPerPeriod(), .05, "Average available");
735 assertFalse(semaphore.isShutdown(), "Already shutdown");
736 assertEquals(LIMIT, semaphore.getLimit(), "Wrong limit");
737 }
738
739
740
741
742
743 @Test
744 void testInitDefaultService() {
745 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD_MILLIS, UNIT, LIMIT);
746 final ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore.getExecutorService();
747 assertFalse(exec.getContinueExistingPeriodicTasksAfterShutdownPolicy(), "Wrong periodic task policy");
748 assertFalse(exec.getExecuteExistingDelayedTasksAfterShutdownPolicy(), "Wrong delayed task policy");
749 assertFalse(exec.isShutdown(), "Already shutdown");
750 semaphore.shutdown();
751 }
752
753
754
755
756
757 @Test
758 void testInitInvalidPeriod() {
759 assertIllegalArgumentException(() -> new TimedSemaphore(0L, UNIT, LIMIT));
760 }
761
762 @Test
763 void testNonFairAcquireNewcomerCanBypassQueuedCaller() throws Exception {
764 final TimedSemaphore semaphore = TimedSemaphore.builder().setPeriod(1).setTimeUnit(TimeUnit.DAYS).setLimit(1).setFair(false).get();
765 assertAcquireOrder(semaphore, false);
766 }
767
768
769
770
771 @Test
772 void testPassAfterShutdown() {
773 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD_MILLIS, UNIT, LIMIT);
774 semaphore.shutdown();
775 assertThrows(IllegalStateException.class, semaphore::acquire);
776 }
777
778
779
780
781
782
783 @Test
784 void testShutdownMultipleTimes() throws InterruptedException {
785 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
786 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
787 prepareStartTimer(service, future);
788 EasyMock.expect(Boolean.valueOf(future.cancel(false))).andReturn(Boolean.TRUE);
789 EasyMock.replay(service, future);
790 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD_MILLIS, UNIT, LIMIT);
791 semaphore.acquire();
792 for (int i = 0; i < 10; i++) {
793 semaphore.shutdown();
794 }
795 EasyMock.verify(service, future);
796 }
797
798
799
800
801
802 @Test
803 void testShutdownOwnExecutor() {
804 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD_MILLIS, UNIT, LIMIT);
805 semaphore.shutdown();
806 assertTrue(semaphore.isShutdown(), "Not shutdown");
807 assertTrue(semaphore.getExecutorService().isShutdown(), "Executor not shutdown");
808 }
809
810
811
812
813
814 @Test
815 void testShutdownSharedExecutorNoTask() {
816 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
817 EasyMock.replay(service);
818 final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD_MILLIS, UNIT, LIMIT);
819 semaphore.shutdown();
820 assertTrue(semaphore.isShutdown(), "Not shutdown");
821 EasyMock.verify(service);
822 }
823
824
825
826
827
828
829
830 @Test
831 void testShutdownSharedExecutorTask() throws InterruptedException {
832 final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
833 final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
834 prepareStartTimer(service, future);
835 EasyMock.expect(Boolean.valueOf(future.cancel(false))).andReturn(Boolean.TRUE);
836 EasyMock.replay(service, future);
837 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD_MILLIS, UNIT, LIMIT);
838 semaphore.acquire();
839 semaphore.shutdown();
840 assertTrue(semaphore.isShutdown(), "Not shutdown");
841 EasyMock.verify(service, future);
842 }
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870 @Test
871 public void testShutdownWakesBlockedAcquireThreads() {
872 assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
873
874
875
876 final TimedSemaphore sem = TimedSemaphore.builder().setPeriod(60).setTimeUnit(TimeUnit.SECONDS).setLimit(1).get();
877 sem.acquire();
878 final Thread blocker = new Thread(() -> {
879 try {
880 sem.acquire();
881 } catch (final InterruptedException e) {
882 Thread.currentThread().interrupt();
883 } catch (final IllegalStateException e) {
884
885 }
886 }, "testShutdownWakesBlockedAcquireThreads");
887 blocker.setDaemon(true);
888 blocker.start();
889
890 final long parkDeadline = System.nanoTime() + Duration.ofSeconds(2).toNanos();
891 while (System.nanoTime() < parkDeadline && blocker.getState() != Thread.State.WAITING) {
892 Thread.sleep(10);
893 }
894 sem.shutdown();
895
896
897
898 blocker.join(5000);
899 assertFalse(blocker.isAlive(), "TimedSemaphore.shutdown() failed to wake thread blocked in acquire(): blocker still alive in state="
900 + blocker.getState() + " 5s after shutdown(). Bug present (shutdown() does not call notifyAll()).");
901 });
902 }
903
904
905
906
907
908
909 @Test
910 void testStartTimer() throws InterruptedException {
911 final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD_MILLIS, UNIT, LIMIT);
912 final ScheduledFuture<?> future = semaphore.startTimer();
913 assertNotNull(future, "No future returned");
914 ThreadUtils.sleepQuietly(DURATION);
915 final int trials = 10;
916 int count = 0;
917 do {
918 Thread.sleep(PERIOD_MILLIS);
919 assertFalse(count++ > trials, "endOfPeriod() not called!");
920 } while (semaphore.getPeriodEnds() <= 0);
921 semaphore.shutdown();
922 }
923
924
925
926
927
928 @Test
929 void testTryAcquire() throws InterruptedException {
930 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD_MILLIS, TimeUnit.SECONDS, LIMIT);
931 final TryAcquireThread[] threads = new TryAcquireThread[3 * LIMIT];
932 final CountDownLatch latch = new CountDownLatch(1);
933 for (int i = 0; i < threads.length; i++) {
934 threads[i] = new TryAcquireThread(semaphore, latch);
935 threads[i].start();
936 }
937 latch.countDown();
938 int permits = 0;
939 for (final TryAcquireThread t : threads) {
940 t.join();
941 if (t.acquired) {
942 permits++;
943 }
944 }
945 assertEquals(LIMIT, permits, "Wrong number of permits granted");
946 }
947
948
949
950
951 @Test
952 void testTryAcquireAfterShutdown() {
953 final TimedSemaphore semaphore = new TimedSemaphore(PERIOD_MILLIS, UNIT, LIMIT);
954 semaphore.shutdown();
955 assertThrows(IllegalStateException.class, semaphore::tryAcquire);
956 }
957
958 }