/
QueuedThreadPoolTest.java
884 lines (762 loc) · 27.7 KB
/
QueuedThreadPoolTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util.thread;
import java.io.Closeable;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.thread.ThreadPool.SizedThreadPool;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class QueuedThreadPoolTest extends AbstractThreadPoolTest
{
private static final Logger LOG = Log.getLogger(QueuedThreadPoolTest.class);
private final AtomicInteger _jobs = new AtomicInteger();
private static class TestQueuedThreadPool extends QueuedThreadPool
{
private final AtomicInteger _started;
private final CountDownLatch _enteredRemoveThread;
private final CountDownLatch _exitRemoveThread;
public TestQueuedThreadPool(AtomicInteger started, CountDownLatch enteredRemoveThread, CountDownLatch exitRemoveThread)
{
_started = started;
_enteredRemoveThread = enteredRemoveThread;
_exitRemoveThread = exitRemoveThread;
}
public void superStartThread()
{
super.startThread();
}
@Override
protected void startThread()
{
switch (_started.incrementAndGet())
{
case 1:
case 2:
case 3:
super.startThread();
break;
case 4:
// deliberately not start thread
break;
default:
throw new IllegalStateException("too many threads started");
}
}
@Override
protected void removeThread(Thread thread)
{
try
{
_enteredRemoveThread.countDown();
_exitRemoveThread.await();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
super.removeThread(thread);
}
}
private class RunningJob implements Runnable
{
final CountDownLatch _run = new CountDownLatch(1);
final CountDownLatch _stopping = new CountDownLatch(1);
final CountDownLatch _stopped = new CountDownLatch(1);
final String _name;
final boolean _fail;
RunningJob()
{
this(null, false);
}
public RunningJob(String name)
{
this(name, false);
}
public RunningJob(String name, boolean fail)
{
_name = name;
_fail = fail;
}
@Override
public void run()
{
try
{
_run.countDown();
_stopping.await();
if (_fail)
throw new IllegalStateException("Testing!");
}
catch (IllegalStateException e)
{
throw e;
}
catch (Exception e)
{
LOG.debug(e);
}
finally
{
_jobs.incrementAndGet();
_stopped.countDown();
}
}
public void stop() throws InterruptedException
{
if (_run.await(10, TimeUnit.SECONDS))
_stopping.countDown();
if (!_stopped.await(10, TimeUnit.SECONDS))
throw new IllegalStateException();
}
@Override
public String toString()
{
if (_name == null)
return super.toString();
return String.format("%s@%x", _name, hashCode());
}
}
private class CloseableJob extends RunningJob implements Closeable
{
final CountDownLatch _closed = new CountDownLatch(1);
@Override
public void close()
{
_closed.countDown();
}
}
@Test
public void testThreadPool() throws Exception
{
QueuedThreadPool tp = new QueuedThreadPool();
tp.setMinThreads(2);
tp.setMaxThreads(4);
tp.setIdleTimeout(1000);
tp.setThreadsPriority(Thread.NORM_PRIORITY - 1);
tp.start();
// min threads started
waitForThreads(tp, 2);
waitForIdle(tp, 2);
// Doesn't shrink to less than min threads
Thread.sleep(3 * tp.getIdleTimeout() / 2);
assertThat(tp.getThreads(), is(2));
assertThat(tp.getIdleThreads(), is(2));
// Run job0
RunningJob job0 = new RunningJob("JOB0");
tp.execute(job0);
assertTrue(job0._run.await(10, TimeUnit.SECONDS));
assertThat(tp.getThreads(), is(2));
assertThat(tp.getIdleThreads(), is(1));
// Run job1
RunningJob job1 = new RunningJob("JOB1");
tp.execute(job1);
assertTrue(job1._run.await(10, TimeUnit.SECONDS));
assertThat(tp.getThreads(), is(2));
assertThat(tp.getIdleThreads(), is(0));
// Run job2
RunningJob job2 = new RunningJob("JOB2");
tp.execute(job2);
assertTrue(job2._run.await(10, TimeUnit.SECONDS));
assertThat(tp.getThreads(), is(3));
assertThat(tp.getIdleThreads(), is(0));
// Run job3
RunningJob job3 = new RunningJob("JOB3");
tp.execute(job3);
assertTrue(job3._run.await(10, TimeUnit.SECONDS));
assertThat(tp.getThreads(), is(4));
assertThat(tp.getIdleThreads(), is(0));
// Check no short term change
Thread.sleep(100);
assertThat(tp.getThreads(), is(4));
assertThat(tp.getIdleThreads(), is(0));
// Run job4. will be queued
RunningJob job4 = new RunningJob("JOB4");
tp.execute(job4);
assertFalse(job4._run.await(250, TimeUnit.MILLISECONDS));
assertThat(tp.getThreads(), is(4));
assertThat(tp.getIdleThreads(), is(0));
assertThat(tp.getQueueSize(), is(1));
// finish job 0
job0._stopping.countDown();
assertTrue(job0._stopped.await(10, TimeUnit.SECONDS));
// job4 should now run
assertTrue(job4._run.await(10, TimeUnit.SECONDS));
assertThat(tp.getThreads(), is(4));
assertThat(tp.getIdleThreads(), is(0));
assertThat(tp.getQueueSize(), is(0));
// finish job 1, and its thread will become idle
job1._stopping.countDown();
assertTrue(job1._stopped.await(10, TimeUnit.SECONDS));
waitForIdle(tp, 1);
waitForThreads(tp, 4);
// finish job 2,3,4
job2._stopping.countDown();
job3._stopping.countDown();
job4._stopping.countDown();
assertTrue(job2._stopped.await(10, TimeUnit.SECONDS));
assertTrue(job3._stopped.await(10, TimeUnit.SECONDS));
assertTrue(job4._stopped.await(10, TimeUnit.SECONDS));
// At beginning of the test we waited 1.5*idleTimeout, but
// never actually shrunk the pool because it was at minThreads.
// Now that all jobs are finished, one thread will figure out
// that it will go idle and will shrink itself out of the pool.
// Give it some time to detect that, but not too much to shrink
// two threads.
Thread.sleep(tp.getIdleTimeout() / 4);
// Now we have 3 idle threads.
waitForIdle(tp, 3);
assertThat(tp.getThreads(), is(3));
tp.stop();
}
@Test
public void testThreadPoolFailingJobs() throws Exception
{
QueuedThreadPool tp = new QueuedThreadPool();
tp.setMinThreads(2);
tp.setMaxThreads(4);
tp.setIdleTimeout(900);
tp.setThreadsPriority(Thread.NORM_PRIORITY - 1);
try (StacklessLogging stackless = new StacklessLogging(QueuedThreadPool.class))
{
tp.start();
// min threads started
waitForThreads(tp, 2);
waitForIdle(tp, 2);
// Doesn't shrink to less than min threads
Thread.sleep(3 * tp.getIdleTimeout() / 2);
waitForThreads(tp, 2);
waitForIdle(tp, 2);
// Run job0
RunningJob job0 = new RunningJob("JOB0", true);
tp.execute(job0);
assertTrue(job0._run.await(10, TimeUnit.SECONDS));
waitForIdle(tp, 1);
// Run job1
RunningJob job1 = new RunningJob("JOB1", true);
tp.execute(job1);
assertTrue(job1._run.await(10, TimeUnit.SECONDS));
waitForThreads(tp, 2);
waitForIdle(tp, 0);
// Run job2
RunningJob job2 = new RunningJob("JOB2", true);
tp.execute(job2);
assertTrue(job2._run.await(10, TimeUnit.SECONDS));
waitForThreads(tp, 3);
waitForIdle(tp, 0);
// Run job3
RunningJob job3 = new RunningJob("JOB3", true);
tp.execute(job3);
assertTrue(job3._run.await(10, TimeUnit.SECONDS));
waitForThreads(tp, 4);
waitForIdle(tp, 0);
assertThat(tp.getIdleThreads(), is(0));
Thread.sleep(100);
assertThat(tp.getIdleThreads(), is(0));
// Run job4. will be queued
RunningJob job4 = new RunningJob("JOB4", true);
tp.execute(job4);
assertFalse(job4._run.await(1, TimeUnit.SECONDS));
// finish job 0
job0._stopping.countDown();
assertTrue(job0._stopped.await(10, TimeUnit.SECONDS));
// job4 should now run
assertTrue(job4._run.await(10, TimeUnit.SECONDS));
assertThat(tp.getThreads(), is(4));
assertThat(tp.getIdleThreads(), is(0));
// finish job 1
job1._stopping.countDown();
assertTrue(job1._stopped.await(10, TimeUnit.SECONDS));
waitForThreads(tp, 3);
assertThat(tp.getIdleThreads(), is(0));
// finish job 2,3,4
job2._stopping.countDown();
job3._stopping.countDown();
job4._stopping.countDown();
assertTrue(job2._stopped.await(10, TimeUnit.SECONDS));
assertTrue(job3._stopped.await(10, TimeUnit.SECONDS));
assertTrue(job4._stopped.await(10, TimeUnit.SECONDS));
waitForIdle(tp, 2);
waitForThreads(tp, 2);
}
tp.stop();
}
@Test
public void testExecuteNoIdleThreads() throws Exception
{
QueuedThreadPool tp = new QueuedThreadPool();
tp.setDetailedDump(true);
tp.setMinThreads(1);
tp.setMaxThreads(10);
tp.setIdleTimeout(500);
tp.start();
RunningJob job1 = new RunningJob();
tp.execute(job1);
RunningJob job2 = new RunningJob();
tp.execute(job2);
RunningJob job3 = new RunningJob();
tp.execute(job3);
// make sure these jobs have started running
assertTrue(job1._run.await(5, TimeUnit.SECONDS));
assertTrue(job2._run.await(5, TimeUnit.SECONDS));
assertTrue(job3._run.await(5, TimeUnit.SECONDS));
waitForThreads(tp, 3);
assertThat(tp.getIdleThreads(), is(0));
job1._stopping.countDown();
assertTrue(job1._stopped.await(10, TimeUnit.SECONDS));
waitForIdle(tp, 1);
assertThat(tp.getThreads(), is(3));
waitForIdle(tp, 0);
assertThat(tp.getThreads(), is(2));
RunningJob job4 = new RunningJob();
tp.execute(job4);
assertTrue(job4._run.await(5, TimeUnit.SECONDS));
tp.stop();
}
@Test
public void testLifeCycleStop() throws Exception
{
QueuedThreadPool tp = new QueuedThreadPool();
tp.setName("TestPool");
tp.setMinThreads(1);
tp.setMaxThreads(2);
tp.setIdleTimeout(900);
tp.setStopTimeout(500);
tp.setThreadsPriority(Thread.NORM_PRIORITY - 1);
tp.start();
// min threads started
waitForThreads(tp, 1);
waitForIdle(tp, 1);
// Run job0 and job1
RunningJob job0 = new RunningJob();
RunningJob job1 = new RunningJob();
tp.execute(job0);
tp.execute(job1);
// Add more jobs (which should not be run)
RunningJob job2 = new RunningJob();
CloseableJob job3 = new CloseableJob();
RunningJob job4 = new RunningJob();
tp.execute(job2);
tp.execute(job3);
tp.execute(job4);
// Wait until the first 2 start running
waitForThreads(tp, 2);
waitForIdle(tp, 0);
assertTrue(job0._run.await(200, TimeUnit.MILLISECONDS));
assertTrue(job1._run.await(200, TimeUnit.MILLISECONDS));
// Queue should be empty after thread pool is stopped
tp.stop();
assertThat(tp.getQueue().size(), is(0));
// First 2 jobs closed by InterruptedException
assertTrue(job0._stopped.await(200, TimeUnit.MILLISECONDS));
assertTrue(job1._stopped.await(200, TimeUnit.MILLISECONDS));
// Verify RunningJobs in the queue have not been run
assertFalse(job2._run.await(200, TimeUnit.MILLISECONDS));
assertFalse(job4._run.await(200, TimeUnit.MILLISECONDS));
// Verify ClosableJobs have not been run but have been closed
assertFalse(job3._run.await(200, TimeUnit.MILLISECONDS));
assertTrue(job3._closed.await(200, TimeUnit.MILLISECONDS));
}
@Test
public void testShrink() throws Exception
{
final AtomicInteger sleep = new AtomicInteger(100);
Runnable job = () ->
{
try
{
Thread.sleep(sleep.get());
}
catch (Exception e)
{
e.printStackTrace();
}
};
QueuedThreadPool tp = new QueuedThreadPool();
tp.setMinThreads(2);
tp.setMaxThreads(10);
tp.setIdleTimeout(400);
tp.setThreadsPriority(Thread.NORM_PRIORITY - 1);
tp.start();
waitForIdle(tp, 2);
waitForThreads(tp, 2);
sleep.set(200);
tp.execute(job);
tp.execute(job);
for (int i = 0; i < 20; i++)
{
tp.execute(job);
}
waitForThreads(tp, 10);
waitForIdle(tp, 0);
sleep.set(5);
for (int i = 0; i < 500; i++)
{
tp.execute(job);
Thread.sleep(10);
}
waitForThreads(tp, 2);
waitForIdle(tp, 2);
tp.stop();
}
@Test
public void testSteadyShrink() throws Exception
{
CountDownLatch latch = new CountDownLatch(1);
Runnable job = () ->
{
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
};
QueuedThreadPool tp = new QueuedThreadPool();
tp.setMinThreads(2);
tp.setMaxThreads(10);
int timeout = 500;
tp.setIdleTimeout(timeout);
tp.setThreadsPriority(Thread.NORM_PRIORITY - 1);
tp.start();
waitForIdle(tp, 2);
waitForThreads(tp, 2);
for (int i = 0; i < 10; i++)
{
tp.execute(job);
}
waitForThreads(tp, 10);
int threads = tp.getThreads();
// let the jobs run
latch.countDown();
for (int i = 5; i-- > 0; )
{
Thread.sleep(timeout / 2);
tp.execute(job);
}
// Assert that steady rate of jobs doesn't prevent some idling out
assertThat(tp.getThreads(), lessThan(threads));
threads = tp.getThreads();
for (int i = 5; i-- > 0; )
{
Thread.sleep(timeout / 2);
tp.execute(job);
}
assertThat(tp.getThreads(), lessThan(threads));
}
@Test
public void testEnsureThreads() throws Exception
{
AtomicInteger started = new AtomicInteger(0);
CountDownLatch enteredRemoveThread = new CountDownLatch(1);
CountDownLatch exitRemoveThread = new CountDownLatch(1);
TestQueuedThreadPool tp = new TestQueuedThreadPool(started, enteredRemoveThread, exitRemoveThread);
tp.setMinThreads(2);
tp.setMaxThreads(10);
tp.setIdleTimeout(400);
tp.setThreadsPriority(Thread.NORM_PRIORITY - 1);
tp.start();
waitForIdle(tp, 2);
waitForThreads(tp, 2);
RunningJob job1 = new RunningJob();
RunningJob job2 = new RunningJob();
RunningJob job3 = new RunningJob();
tp.execute(job1);
tp.execute(job2);
tp.execute(job3);
waitForThreads(tp, 3);
waitForIdle(tp, 0);
// We stop job3, the thread becomes idle, thread decides to shrink, and then blocks in removeThread().
job3.stop();
assertTrue(enteredRemoveThread.await(5, TimeUnit.SECONDS));
waitForThreads(tp, 3);
waitForIdle(tp, 1);
// Executing job4 will not start a new thread because we already have 1 idle thread.
RunningJob job4 = new RunningJob();
tp.execute(job4);
// Allow thread to exit from removeThread().
// The 4th thread is not actually started in our startThread() until tp.superStartThread() is called.
// Delay by 1000ms to check that ensureThreads is only starting one thread even though it is slow to start.
assertThat(started.get(), is(3));
exitRemoveThread.countDown();
Thread.sleep(1000);
// Now startThreads() should have been called 4 times.
// Actually start the thread, and job4 should be run.
assertThat(started.get(), is(4));
tp.superStartThread();
assertTrue(job4._run.await(5, TimeUnit.SECONDS));
job1.stop();
job2.stop();
job4.stop();
tp.stop();
}
@Test
public void testMaxStopTime() throws Exception
{
QueuedThreadPool tp = new QueuedThreadPool();
long stopTimeout = 500;
tp.setStopTimeout(stopTimeout);
tp.start();
CountDownLatch interruptedLatch = new CountDownLatch(1);
tp.execute(() ->
{
try
{
Thread.sleep(10 * stopTimeout);
}
catch (InterruptedException expected)
{
interruptedLatch.countDown();
}
});
long beforeStop = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
tp.stop();
long afterStop = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
assertTrue(tp.isStopped());
assertTrue(afterStop - beforeStop < 1000);
assertTrue(interruptedLatch.await(5, TimeUnit.SECONDS));
}
private void waitForIdle(QueuedThreadPool tp, int idle)
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = now;
while (tp.getIdleThreads() != idle && (now - start) < 10000)
{
try
{
Thread.sleep(50);
}
catch (InterruptedException ignored)
{
}
now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
}
assertThat(tp.getIdleThreads(), is(idle));
}
private void waitForReserved(QueuedThreadPool tp, int reserved)
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = now;
ReservedThreadExecutor reservedThreadExecutor = tp.getBean(ReservedThreadExecutor.class);
while (reservedThreadExecutor.getAvailable() != reserved && (now - start) < 10000)
{
try
{
Thread.sleep(50);
}
catch (InterruptedException ignored)
{
}
now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
}
assertThat(reservedThreadExecutor.getAvailable(), is(reserved));
}
private void waitForThreads(QueuedThreadPool tp, int threads)
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = now;
while (tp.getThreads() != threads && (now - start) < 10000)
{
try
{
Thread.sleep(50);
}
catch (InterruptedException ignored)
{
}
now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
}
assertThat(tp.getThreads(), is(threads));
}
@Test
public void testException() throws Exception
{
QueuedThreadPool tp = new QueuedThreadPool();
tp.setMinThreads(5);
tp.setMaxThreads(10);
tp.setIdleTimeout(1000);
tp.start();
try (StacklessLogging stackless = new StacklessLogging(QueuedThreadPool.class))
{
tp.execute(() ->
{
throw new IllegalStateException();
});
tp.execute(() ->
{
throw new Error();
});
tp.execute(() ->
{
throw new RuntimeException();
});
tp.execute(() ->
{
throw new ThreadDeath();
});
Thread.sleep(100);
assertThat(tp.getThreads(), greaterThanOrEqualTo(5));
}
tp.stop();
}
@Test
public void testZeroMinThreads() throws Exception
{
int maxThreads = 10;
int minThreads = 0;
QueuedThreadPool pool = new QueuedThreadPool(maxThreads, minThreads);
pool.start();
final CountDownLatch latch = new CountDownLatch(1);
pool.execute(latch::countDown);
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testConstructorMinMaxThreadsValidation()
{
assertThrows(IllegalArgumentException.class, () -> new QueuedThreadPool(4, 8));
}
@Test
public void testDump() throws Exception
{
QueuedThreadPool pool = new QueuedThreadPool(4, 3);
pool.setIdleTimeout(10000);
String dump = pool.dump();
// TODO use hamcrest 2.0 regex matcher
assertThat(dump, containsString("STOPPED"));
assertThat(dump, containsString(",3<=0<=4,i=0,r=-1,q=0"));
assertThat(dump, containsString("[NO_TRY]"));
pool.setReservedThreads(2);
dump = pool.dump();
assertThat(dump, containsString("STOPPED"));
assertThat(dump, containsString(",3<=0<=4,i=0,r=2,q=0"));
assertThat(dump, containsString("[NO_TRY]"));
pool.start();
waitForIdle(pool, 3);
Thread.sleep(250); // TODO need to give time for threads to read idle poll after setting idle
dump = pool.dump();
assertThat(count(dump, " - STARTED"), is(2));
assertThat(dump, containsString(",3<=3<=4,i=3,r=2,q=0"));
assertThat(dump, containsString("[ReservedThreadExecutor@"));
assertThat(count(dump, " IDLE"), is(3));
assertThat(count(dump, " RESERVED"), is(0));
CountDownLatch started = new CountDownLatch(1);
CountDownLatch waiting = new CountDownLatch(1);
pool.execute(() ->
{
try
{
started.countDown();
waiting.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
});
started.await();
Thread.sleep(250); // TODO need to give time for threads to read idle poll after setting idle
dump = pool.dump();
assertThat(count(dump, " - STARTED"), is(2));
assertThat(dump, containsString(",3<=3<=4,i=2,r=2,q=0"));
assertThat(dump, containsString("[ReservedThreadExecutor@"));
assertThat(count(dump, " IDLE"), is(2));
assertThat(count(dump, " WAITING"), is(1));
assertThat(count(dump, " RESERVED"), is(0));
assertThat(count(dump, "QueuedThreadPoolTest.lambda$testDump$"), is(0));
pool.setDetailedDump(true);
dump = pool.dump();
assertThat(count(dump, " - STARTED"), is(2));
assertThat(dump, containsString(",3<=3<=4,i=2,r=2,q=0"));
assertThat(dump, containsString("s=0/2"));
assertThat(dump, containsString("[ReservedThreadExecutor@"));
assertThat(count(dump, " IDLE"), is(2));
assertThat(count(dump, " WAITING"), is(1));
assertThat(count(dump, " RESERVED"), is(0));
assertThat(count(dump, "QueuedThreadPoolTest.lambda$testDump$"), is(1));
assertFalse(pool.tryExecute(() ->
{
}));
waitForReserved(pool, 1);
Thread.sleep(250); // TODO need to give time for threads to read idle poll after setting idle
dump = pool.dump();
assertThat(count(dump, " - STARTED"), is(2));
assertThat(dump, containsString(",3<=3<=4,i=1,r=2,q=0"));
assertThat(dump, containsString("s=1/2"));
assertThat(dump, containsString("[ReservedThreadExecutor@"));
assertThat(count(dump, " IDLE"), is(1));
assertThat(count(dump, " WAITING"), is(1));
assertThat(count(dump, " RESERVED"), is(1));
assertThat(count(dump, "QueuedThreadPoolTest.lambda$testDump$"), is(1));
}
@Test
public void testContextClassLoader() throws Exception
{
QueuedThreadPool tp = new QueuedThreadPool();
tp.setMinThreads(1);
tp.setMaxThreads(3);
tp.setIdleTimeout(1000);
tp.setThreadsPriority(Thread.NORM_PRIORITY - 1);
try (StacklessLogging stackless = new StacklessLogging(QueuedThreadPool.class))
{
//change the current thread's classloader to something else
Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[] {}));
//create a new thread
Thread t = tp.newThread(() ->
{
//the executing thread should be still set to the classloader of the QueuedThreadPool,
//not that of the thread that created this thread.
assertThat(Thread.currentThread().getContextClassLoader(), Matchers.equalTo(QueuedThreadPool.class.getClassLoader()));
});
//new thread should be set to the classloader of the QueuedThreadPool
assertThat(t.getContextClassLoader(), Matchers.equalTo(QueuedThreadPool.class.getClassLoader()));
t.start();
}
}
private int count(String s, String p)
{
int c = 0;
int i = s.indexOf(p);
while (i >= 0)
{
c++;
i = s.indexOf(p, i + 1);
}
return c;
}
@Override
protected SizedThreadPool newPool(int max)
{
return new QueuedThreadPool(max);
}
}