1 18 package org.apache.activemq.transport.nio; 19 20 import java.io.IOException ; 21 import java.nio.channels.SocketChannel ; 22 import java.util.LinkedList ; 23 import java.util.concurrent.Executor ; 24 import java.util.concurrent.Executors ; 25 import java.util.concurrent.ThreadFactory ; 26 27 36 final public class SelectorManager { 37 38 static final public SelectorManager singleton = new SelectorManager(); 39 static SelectorManager getInstance() { 40 return singleton; 41 } 42 43 public interface Listener { 44 public void onSelect(SelectorSelection selector); 45 public void onError(SelectorSelection selection, Throwable error); 46 } 47 48 private Executor selectorExecutor = Executors.newCachedThreadPool(new ThreadFactory (){ 49 public Thread newThread(Runnable r) { 50 Thread rc = new Thread (r); 51 rc.setName("NIO Transport Thread"); 52 return rc; 53 }}); 54 private Executor channelExecutor = selectorExecutor; 55 private LinkedList <SelectorWorker> freeWorkers = new LinkedList <SelectorWorker>(); 56 private int maxChannelsPerWorker = 64; 57 58 public synchronized SelectorSelection register(SocketChannel socketChannel, Listener listener) 59 throws IOException { 60 61 SelectorWorker worker = null; 62 if (freeWorkers.size() > 0) { 63 worker = freeWorkers.getFirst(); 64 } else { 65 worker = new SelectorWorker(this); 66 freeWorkers.addFirst(worker); 67 } 68 69 SelectorSelection selection = new SelectorSelection(worker, socketChannel, listener); 70 return selection; 71 } 72 73 synchronized void onWorkerFullEvent(SelectorWorker worker) { 74 freeWorkers.remove(worker); 75 } 76 77 synchronized public void onWorkerEmptyEvent(SelectorWorker worker) { 78 freeWorkers.remove(worker); 79 } 80 81 synchronized public void onWorkerNotFullEvent(SelectorWorker worker) { 82 freeWorkers.add(worker); 83 } 84 85 public Executor getChannelExecutor() { 86 return channelExecutor; 87 } 88 89 public void setChannelExecutor(Executor channelExecutor) { 90 this.channelExecutor = channelExecutor; 91 } 92 93 public int getMaxChannelsPerWorker() { 94 return maxChannelsPerWorker; 95 } 96 97 public void setMaxChannelsPerWorker(int maxChannelsPerWorker) { 98 this.maxChannelsPerWorker = maxChannelsPerWorker; 99 } 100 101 public Executor getSelectorExecutor() { 102 return selectorExecutor; 103 } 104 105 public void setSelectorExecutor(Executor selectorExecutor) { 106 this.selectorExecutor = selectorExecutor; 107 } 108 109 } 110 | Popular Tags |