1
+ /*
2
+ * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3
+ */
4
+
5
+ import kotlinx.coroutines.experimental.*
6
+ import org.junit.*
7
+ import org.junit.Assert.*
8
+ import java.lang.reflect.*
9
+ import java.util.concurrent.*
10
+
11
+ class CommonPoolTest {
12
+ private inline fun <T > Try (block : () -> T ) = try { block() } catch (e: Throwable ) { null }
13
+
14
+ @Test
15
+ fun testIsGoodCommonPool () {
16
+ // Test only on JDKs that has all we need
17
+ val fjpClass = Try { Class .forName(" java.util.concurrent.ForkJoinPool" ) } ? : return
18
+ val wtfClass = Try { Class .forName(" java.util.concurrent.ForkJoinPool${' $' } ForkJoinWorkerThreadFactory" ) } ? : return
19
+ val dwtfClass = Try { Class .forName(" java.util.concurrent.ForkJoinPool${' $' } DefaultForkJoinWorkerThreadFactory" ) } ? : return
20
+ // We need private constructor to create "broken" FJP instance
21
+ val fjpCtor = Try { fjpClass.getDeclaredConstructor(
22
+ Int ::class .java,
23
+ wtfClass,
24
+ Thread .UncaughtExceptionHandler ::class .java,
25
+ Int ::class .java,
26
+ String ::class .java
27
+ ) } ? : return
28
+ fjpCtor.isAccessible = true
29
+ val dwtfCtor = Try { dwtfClass.getDeclaredConstructor() } ? : return
30
+ dwtfCtor.isAccessible = true
31
+ // Create bad pool
32
+ val fjp0: ExecutorService = createFJP(0 , fjpCtor, dwtfCtor) ? : return
33
+ assertFalse(CommonPool .isGoodCommonPool(fjpClass, fjp0))
34
+ fjp0.shutdown()
35
+ // Create good pool
36
+ val fjp1: ExecutorService = createFJP(1 , fjpCtor, dwtfCtor) ? : return
37
+ assertTrue(CommonPool .isGoodCommonPool(fjpClass, fjp1))
38
+ fjp1.shutdown()
39
+ println (" CommonPool.isGoodCommonPool test passed" )
40
+ }
41
+
42
+ fun createFJP (
43
+ parallelism : Int ,
44
+ fjpCtor : Constructor <out Any >,
45
+ dwtfCtor : Constructor <out Any >
46
+ ): ExecutorService ? = Try {
47
+ fjpCtor.newInstance(
48
+ parallelism,
49
+ dwtfCtor.newInstance(),
50
+ Thread .getDefaultUncaughtExceptionHandler(),
51
+ 0 ,
52
+ " Worker"
53
+ )
54
+ } as ? ExecutorService
55
+ }
0 commit comments