1 |
/* |
2 |
* Written by Martin Buchholz and Jason Mehrens with assistance from |
3 |
* members of JCP JSR-166 Expert Group and released to the public |
4 |
* domain, as explained at |
5 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
6 |
*/ |
7 |
|
8 |
/* |
9 |
* @test |
10 |
* @summary Only one thread should be created when a thread needs to |
11 |
* be kept alive to service a delayed task waiting in the queue. |
12 |
* @library /lib/testlibrary/ |
13 |
*/ |
14 |
|
15 |
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
16 |
|
17 |
import java.util.concurrent.ScheduledThreadPoolExecutor; |
18 |
import java.util.concurrent.ThreadFactory; |
19 |
import java.util.concurrent.atomic.AtomicLong; |
20 |
import jdk.testlibrary.Utils; |
21 |
|
22 |
public class ThreadRestarts { |
23 |
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000); |
24 |
static final long FAR_FUTURE_MS = 10 * LONG_DELAY_MS; |
25 |
|
26 |
public static void main(String[] args) throws Exception { |
27 |
test(false); |
28 |
test(true); |
29 |
} |
30 |
|
31 |
private static void test(boolean allowTimeout) throws Exception { |
32 |
CountingThreadFactory ctf = new CountingThreadFactory(); |
33 |
ScheduledThreadPoolExecutor stpe |
34 |
= new ScheduledThreadPoolExecutor(10, ctf); |
35 |
try { |
36 |
// schedule a dummy task in the "far future" |
37 |
Runnable nop = new Runnable() { public void run() {}}; |
38 |
stpe.schedule(nop, FAR_FUTURE_MS, MILLISECONDS); |
39 |
stpe.setKeepAliveTime(1L, MILLISECONDS); |
40 |
stpe.allowCoreThreadTimeOut(allowTimeout); |
41 |
MILLISECONDS.sleep(12L); |
42 |
} finally { |
43 |
stpe.shutdownNow(); |
44 |
if (!stpe.awaitTermination(LONG_DELAY_MS, MILLISECONDS)) |
45 |
throw new AssertionError("timed out"); |
46 |
} |
47 |
if (ctf.count.get() > 1) |
48 |
throw new AssertionError( |
49 |
String.format("%d threads created, 1 expected", |
50 |
ctf.count.get())); |
51 |
} |
52 |
|
53 |
static class CountingThreadFactory implements ThreadFactory { |
54 |
final AtomicLong count = new AtomicLong(0L); |
55 |
|
56 |
public Thread newThread(Runnable r) { |
57 |
count.getAndIncrement(); |
58 |
Thread t = new Thread(r); |
59 |
t.setDaemon(true); |
60 |
return t; |
61 |
} |
62 |
} |
63 |
} |