1 | package diskCacheV111.util; |
2 | |
3 | import java.util.concurrent.SynchronousQueue; |
4 | import java.util.concurrent.ThreadPoolExecutor; |
5 | import java.util.concurrent.TimeUnit; |
6 | import java.util.concurrent.ThreadFactory; |
7 | import java.util.concurrent.Executors; |
8 | |
9 | import dmg.cells.nucleus.CellAdapter; |
10 | import dmg.cells.nucleus.CDC; |
11 | |
12 | import org.dcache.util.CDCThreadFactory; |
13 | import org.dcache.util.FireAndForgetTask; |
14 | |
15 | /** |
16 | * |
17 | * ThreadPoolNG ( Thread Pool New Generation is a |
18 | * java concurrent based implementation of dCache |
19 | * Thread pool. While it's nothing else than wrapper |
20 | * around ThreadPoolExecutor, it's better to replace all |
21 | * instances of ThreadPool with pure ThreadPoolExecutor. |
22 | * |
23 | * @since 1.8 |
24 | */ |
25 | public class ThreadPoolNG implements ThreadPool { |
26 | |
27 | private static final int CORE_SIZE = 0; |
28 | private static final int MAX_SIZE = Integer.MAX_VALUE; |
29 | private static final long KEEP_ALIVE = 60L; |
30 | |
31 | private final ThreadPoolExecutor _executor; |
32 | |
33 | public ThreadPoolNG(CellAdapter cell) |
34 | { |
35 | this(cell.getNucleus()); |
36 | } |
37 | |
38 | public ThreadPoolNG() |
39 | { |
40 | this(Executors.defaultThreadFactory()); |
41 | } |
42 | |
43 | private ThreadPoolNG(ThreadFactory factory) |
44 | { |
45 | _executor = new ThreadPoolExecutor(CORE_SIZE, |
46 | MAX_SIZE, |
47 | KEEP_ALIVE, |
48 | TimeUnit.SECONDS, |
49 | new SynchronousQueue<Runnable>(), |
50 | new CDCThreadFactory(factory)); |
51 | } |
52 | |
53 | |
54 | public int getCurrentThreadCount() { |
55 | return _executor.getActiveCount(); |
56 | } |
57 | |
58 | public int getMaxThreadCount() { |
59 | return _executor.getMaximumPoolSize(); |
60 | } |
61 | |
62 | public int getWaitingThreadCount() { |
63 | return 0; |
64 | } |
65 | |
66 | public void invokeLater(final Runnable runner, String name) |
67 | { |
68 | final CDC cdc = new CDC(); |
69 | Runnable wrapper = new Runnable() { |
70 | public void run() |
71 | { |
72 | cdc.apply(); |
73 | try { |
74 | runner.run(); |
75 | } finally { |
76 | CDC.clear(); |
77 | } |
78 | } |
79 | }; |
80 | |
81 | _executor.execute(new FireAndForgetTask(wrapper)); |
82 | } |
83 | |
84 | public void setMaxThreadCount(int maxThreadCount) |
85 | throws IllegalArgumentException { |
86 | |
87 | /* |
88 | * Be backward compatible with |
89 | */ |
90 | if(maxThreadCount == 0) |
91 | maxThreadCount = MAX_SIZE; |
92 | |
93 | _executor.setMaximumPoolSize(maxThreadCount); |
94 | } |
95 | |
96 | public String toString() { |
97 | return "ThreadPoolNG $Revision: 1.4 $ max/active: " + getMaxThreadCount() + "/" + getCurrentThreadCount(); |
98 | } |
99 | } |