|
20 | 20 |
|
21 | 21 | import java.util.concurrent.ExecutorService; |
22 | 22 | import java.util.concurrent.Executors; |
| 23 | +import java.util.concurrent.LinkedBlockingQueue; |
| 24 | +import java.util.concurrent.ThreadFactory; |
| 25 | +import java.util.concurrent.ThreadPoolExecutor; |
| 26 | +import java.util.concurrent.TimeUnit; |
| 27 | +import java.util.concurrent.atomic.AtomicInteger; |
| 28 | + |
23 | 29 |
|
24 | 30 | public class ThreadPoolService |
25 | 31 | { |
26 | | - private static volatile ExecutorService threadPoolExecutor; |
27 | | - private final static int corePoolSize = 10; |
| 32 | + private final static ExecutorService threadPoolExecutor; |
| 33 | + private final static int MAX_THREAD_POOL_SIZE = 10; |
28 | 34 |
|
| 35 | + static |
| 36 | + { |
| 37 | + if (Backendless.isCodeRunner()) |
| 38 | + threadPoolExecutor = new ThreadPoolExecutor(0, MAX_THREAD_POOL_SIZE, 2, TimeUnit.SECONDS, |
| 39 | + new LinkedBlockingQueue<Runnable>(), |
| 40 | + new SimpleThreadFactory("BackendlessSDK_CR")); |
| 41 | + else |
| 42 | + threadPoolExecutor = new ThreadPoolExecutor(2, MAX_THREAD_POOL_SIZE, 60, TimeUnit.SECONDS, |
| 43 | + new LinkedBlockingQueue<Runnable>(), |
| 44 | + new SimpleThreadFactory("BackendlessSDK")); |
| 45 | + |
| 46 | + } |
| 47 | + |
29 | 48 | public static ExecutorService getPoolExecutor() |
30 | 49 | { |
31 | | - if( threadPoolExecutor == null ) |
| 50 | + return threadPoolExecutor; |
| 51 | + } |
| 52 | + |
| 53 | + private static class SimpleThreadFactory implements ThreadFactory |
| 54 | + { |
| 55 | + private final ThreadFactory threadFactory = Executors.defaultThreadFactory(); |
| 56 | + private final String threadNamePrefix; |
| 57 | + private final boolean isDaemon = true; |
| 58 | + private final AtomicInteger threadNumber = new AtomicInteger(); |
| 59 | + |
| 60 | + public SimpleThreadFactory( String poolName ) |
32 | 61 | { |
33 | | - synchronized( ThreadPoolService.class ) |
34 | | - { |
35 | | - if( threadPoolExecutor == null ) |
36 | | - threadPoolExecutor = Executors.newFixedThreadPool( corePoolSize ); |
37 | | - } |
| 62 | + this.threadNamePrefix = "pool-" + poolName + "-thread-"; |
| 63 | + } |
| 64 | + |
| 65 | + @Override |
| 66 | + public Thread newThread( Runnable r ) |
| 67 | + { |
| 68 | + Thread t = threadFactory.newThread( r ); |
| 69 | + t.setName( threadNamePrefix + threadNumber.getAndIncrement() ); |
| 70 | + t.setDaemon( isDaemon ); |
| 71 | + return t; |
38 | 72 | } |
39 | | - |
40 | | - return threadPoolExecutor; |
41 | 73 | } |
42 | 74 | } |
0 commit comments