Netty 系列目錄 (http://www.javashuo.com/article/p-hskusway-em.html)html
Doug Lea 大神的《Scalable IO in Java》http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf:可伸縮的 IO 模型java
大部分 IO 都是下面這個步驟,react
傳統的 IO 模型是一個 socket 一個線程,代碼以下:緩存
class Server implements Runnable { public void run() { try { ServerSocket ss = new ServerSocket(PORT); while (!Thread.interrupted()) new Thread(new Handler(ss.accept())).start(); //建立新線程來handle // or, single-threaded, or a thread pool } catch (IOException ex) { /* ... */ } } static class Handler implements Runnable { final Socket socket; Handler(Socket s) { socket = s; } public void run() { try { byte[] input = new byte[MAX_INPUT]; socket.getInputStream().read(input); byte[] output = process(input); socket.getOutputStream().write(output); } catch (IOException ex) { /* ... */ } } private byte[] process(byte[] cmd) { /* ... */ } } }
顯然簡單的多線程會帶來擴展性問題,當 client 數量變的不少的時候,還其餘的可用性、性能的問題。解決方法就是 Divide-and-conquer,分開後,就須要 Event-driven Designs 來串聯起來...網絡
全部事情 read、process、write 都由單個線程完成,完成一步從新設置下一步的 event。問題固然就是,其中任何步驟阻塞其它任務就阻塞了,由於只有一個線程。多線程
class Reactor implements Runnable { final Selector selector; final ServerSocketChannel serverSocket; Reactor(int port) throws IOException { // Reactor 初始化 selector = Selector.open(); serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(port)); serverSocket.configureBlocking(false); // 非阻塞 SelectionKey sk = serverSocket.register(selector, SelectionKey.OP_ACCEPT); // 分步處理,第一步,接收accept事件 sk.attach(new Acceptor()); //attach callback object, Acceptor } public void run() { try { while (!Thread.interrupted()) { selector.select(); Set selected = selector.selectedKeys(); Iterator it = selected.iterator(); while (it.hasNext()) dispatch((SelectionKey)(it.next()); //Reactor負責dispatch收到的事件 selected.clear(); } } catch (IOException ex) { /* ... */ } } void dispatch(SelectionKey k) { Runnable r = (Runnable)(k.attachment()); //調用以前註冊的callback對象 if (r != null) r.run(); } class Acceptor implements Runnable { // inner public void run() { try { SocketChannel c = serverSocket.accept(); if (c != null) new Handler(selector, c); } catch(IOException ex) { /* ... */ } } } } final class Handler implements Runnable { final SocketChannel socket; final SelectionKey sk; ByteBuffer input = ByteBuffer.allocate(MAXIN); ByteBuffer output = ByteBuffer.allocate(MAXOUT); static final int READING = 0, SENDING = 1; int state = READING; Handler(Selector sel, SocketChannel c) throws IOException { socket = c; c.configureBlocking(false); // Optionally try first read now sk = socket.register(sel, 0); sk.attach(this); //將Handler做爲callback對象 sk.interestOps(SelectionKey.OP_READ); //第二步,接收Read事件 sel.wakeup(); } boolean inputIsComplete() { /* ... */ } boolean outputIsComplete() { /* ... */ } void process() { /* ... */ } public void run() { try { if (state == READING) read(); else if (state == SENDING) send(); } catch (IOException ex) { /* ... */ } } void read() throws IOException { socket.read(input); if (inputIsComplete()) { process(); state = SENDING; // Normally also do first write now sk.interestOps(SelectionKey.OP_WRITE); //第三步,接收write事件 } } void send() throws IOException { socket.write(output); if (outputIsComplete()) sk.cancel(); //write完就結束了, 關閉select key } } //上面 的實現用Handler來同時處理Read和Write事件, 因此裏面出現狀態判斷 //咱們能夠用State-Object pattern來更優雅的實現 class Handler { // ... public void run() { // initial state is reader socket.read(input); if (inputIsComplete()) { process(); sk.attach(new Sender()); //狀態遷移, Read後變成write, 用Sender做爲新的callback對象 sk.interest(SelectionKey.OP_WRITE); sk.selector().wakeup(); } } class Sender implements Runnable { public void run(){ // ... socket.write(output); if (outputIsComplete()) sk.cancel(); } } }
單線程模式的侷限仍是比較明顯的。因此改進是將比較耗時的部分,從 reactor 線程中分離出去,讓 reactor 專門負責 IO,而另外建立 Thread Pool 和 queue 來緩存和處理任務。因此其實已經進化成 Proactor 模式,異步模式。異步
class Handler implements Runnable { // uses util.concurrent thread pool static PooledExecutor pool = new PooledExecutor(...); static final int PROCESSING = 3; // ... synchronized void read() { // ... socket.read(input); if (inputIsComplete()) { state = PROCESSING; pool.execute(new Processer()); //使用線程pool異步執行 } } synchronized void processAndHandOff() { process(); state = SENDING; // or rebind attachment sk.interest(SelectionKey.OP_WRITE); //process完,開始等待write事件 } class Processer implements Runnable { public void run() { processAndHandOff(); } } }
使用多個 reactor 進程,主 reactor 只負責 accept,而後將接收到的 socketchannel 交給 Thread Pool 去處理。socket
Selector[] selectors; // 一個 selector 表明一個 subReactor int next = 0; class Acceptor { // ... public synchronized void run() { ... Socket connection = serverSocket.accept(); // 主 selector 負責 accept if (connection != null) new Handler(selectors[next], connection); //選個 subReactor 去負責接收到的 connection if (++next == selectors.length) next = 0; } }
天天用心記錄一點點。內容也許不重要,但習慣很重要!ide