1 20 package org.apache.mina.common; 21 22 import java.util.HashMap ; 23 import java.util.Map ; 24 import java.util.concurrent.Executor ; 25 import java.util.concurrent.ThreadFactory ; 26 import java.util.concurrent.ThreadPoolExecutor ; 27 import java.util.concurrent.atomic.AtomicInteger ; 28 29 import org.apache.mina.filter.executor.ExecutorFilter; 30 31 40 public class ExecutorThreadModel implements ThreadModel { 41 45 private static final Map <String , ExecutorThreadModel> service2model = new HashMap <String , ExecutorThreadModel>(); 46 47 55 public static ExecutorThreadModel getInstance(String serviceName) { 56 if (serviceName == null) { 57 throw new NullPointerException ("serviceName"); 58 } 59 60 ExecutorThreadModel model; 61 synchronized (service2model) { 62 model = service2model.get(serviceName); 63 if (model == null) { 64 model = new ExecutorThreadModel(serviceName); 65 service2model.put(serviceName, model); 66 } 67 } 68 69 return model; 70 } 71 72 private final String threadNamePrefix; 73 74 private final ExecutorFilter defaultFilter; 75 76 private ExecutorFilter filter = new ExecutorFilter(); 77 78 private ExecutorThreadModel(String threadNamePrefix) { 79 this.threadNamePrefix = threadNamePrefix; 80 81 defaultFilter = new ExecutorFilter(); 83 ThreadPoolExecutor tpe = (ThreadPoolExecutor ) defaultFilter 84 .getExecutor(); 85 final ThreadFactory originalThreadFactory = tpe.getThreadFactory(); 86 ThreadFactory newThreadFactory = new ThreadFactory () { 87 private final AtomicInteger threadId = new AtomicInteger (0); 88 89 public Thread newThread(Runnable runnable) { 90 Thread t = originalThreadFactory.newThread(runnable); 91 t.setName(ExecutorThreadModel.this.threadNamePrefix + '-' 92 + threadId.incrementAndGet()); 93 t.setDaemon(true); 94 return t; 95 } 96 }; 97 tpe.setThreadFactory(newThreadFactory); 98 99 setExecutor(null); 101 } 102 103 108 public Executor getExecutor() { 109 return filter.getExecutor(); 110 } 111 112 119 public void setExecutor(Executor executor) { 120 if (executor == null) { 121 filter = defaultFilter; 122 } else { 123 filter = new ExecutorFilter(executor); 124 } 125 } 126 127 public void buildFilterChain(IoFilterChain chain) throws Exception { 128 chain.addFirst(ExecutorThreadModel.class.getName(), filter); 129 } 130 } 131 | Popular Tags |