Scalable IO in Java
Scalable IO in Java
http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf
大部分IO都是下面这个步骤,
Most have same basic structure:
Read request
Decode request
Process service
Encode reply
Send reply
关键是如何处理并发, 最原始就是单纯的用多线程

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来串联起来...
单线程版本的Reactor, 所有事情read, process, write都由单个线程完成, 完成一步重新设置下一步的event, 然后干其他的事
问题当然就是, 其中任何步骤不能消耗太多时间, 因为只有一个线程, 你占住了就会block其他任务
ps, 不明白为什么要画那么大个acceptor, 只是作为第一步的callback对象...

看代码会更清楚,
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交给subReactor去listen和处理
当然也可以在subReactor下加上线程池进行异步处理
坦白的说, 没看出用多个reactor有啥大的提升, 降低mainReactor listen的负担?

Selector[] selectors; //subReactors集合, 一个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;
}
}
Scalable IO in Java的更多相关文章
- 《Scalable IO in Java》笔记
Scalable IO in Java http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf 基本上所有的网络处理程序都有以下基本的处理过程:Read reque ...
- 【精尽Netty源码解析】1.Scalable IO in Java——多Reactor的代码实现
Java高伸缩性IO处理 在Doug Lea大神的经典NIO框架文章<Scalable IO in Java>中,具体阐述了如何把Reactor模式和Java NIO整合起来,一步步理论结 ...
- Netty Reator(二)Scalable IO in Java
Netty Reator(二)Scalable IO in Java Netty 系列目录 (https://www.cnblogs.com/binarylei/p/10117436.html) Do ...
- 《Scalable IO in Java》译文
<Scalable IO in Java> 是java.util.concurrent包的作者,大师Doug Lea关于分析与构建可伸缩的高性能IO服务的一篇经典文章,在文章中Doug L ...
- 学习 Doug Lea 大神写的——Scalable IO in Java
学习 Doug Lea 大神写的--Scalable IO in Java 网络服务 Web services.分布式对象等等都具有相同的处理结构 Read request Decode reques ...
- 一文弄懂-《Scalable IO In Java》
目录 一. <Scalable IO In Java> 是什么? 二. IO架构的演变历程 1. Classic Service Designs 经典服务模型 2. Event-drive ...
- Scalable IO in Java【java高效IO】
第一次翻译,如有错误,请指正 1.Outline 大纲Scalable network services 高效网络服务 Event-driven processing 事件驱动处理 Reactor ...
- 【转载】高性能IO设计 & Java NIO & 同步/异步 阻塞/非阻塞 Reactor/Proactor
开始准备看Java NIO的,这篇文章:http://xly1981.iteye.com/blog/1735862 里面提到了这篇文章 http://xmuzyq.iteye.com/blog/783 ...
- hive运行query语句时提示错误:org.apache.hadoop.ipc.RemoteException: java.io.IOException: java.io.IOException:
hive> select product_id, track_time from trackinfo limit 5; Total MapReduce jobs = 1 Launching Jo ...
随机推荐
- python3操作mysql教程
一.下载\安装\配置 1. python3 Python3下载网址:http://www.python.org/getit/ 当前最新版本是python3.2,下载地址是 http://www.pyt ...
- Freeswitch中文用户手册(第四章 SIP)----2
通过 B2BUA 呼叫 在真实世界中,bob 和 alice 肯定要经常改变位置,那么它们的 SIP 地址也会相应改变,并且,如果他们之中有一个或两个处于 NAT 的网络中时,直接通信就更困难了.所以 ...
- 在Visual Studio 2013顯示SCSS詳細錯誤訊息
在WebEssentials套件加持之下,Visual Studio 2013可以直接編修SCSS,每次存檔自動編譯出css.min.css及.map,非常方便.但初心者如我,寫錯語法在所難免,一旦造 ...
- Openresty配置文件上传下载
1. 下载包安装Openresty openresty-1.13.6.1下载地址 https://openresty.org/download/openresty-1.13.6.1.tar.gz 安装 ...
- Atitit 插件机制原理与设计微内核 c# java 的实现attilax总结
Atitit 插件机制原理与设计微内核 c# java 的实现attilax总结 1. 微内核与插件的优点1 2. 插件的注册与使用2 2.1. Ioc容器中注册插件2 2.2. 启动器微内核启动3 ...
- Java创建多线程的三种方法
Java多线程实现方式主要有三种:继承Thread类.实现Runnable接口.使用ExecutorService.Callable.Future实现有返回结果的多线程.其中前两种方式线程执行完后都没 ...
- ubuntu 安装python3.5
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz xz -d Python-.tar.xz .tar cd Python ...
- jedis CodedInputStream encountered a malformed varint
原因:从redis数据库中根据String类型的参数取数据时报的异常 解决方法:应该用字节数组读取低层次的数据,因为是我们自定义的一些对象格式,如图: 这样就不报错了,可以正常读取redis数据库中的 ...
- Jquery学习笔记(10)--ajax删除用户,使用了js原生ajax
主要复习了php的pdo数据库操作,和js的ajax,真麻烦,希望jquery的ajax简单点. index.php: <!DOCTYPE html> <html lang=&quo ...
- java @override 报错处理
转载自:http://blog.sina.com.cn/s/blog_9c7605530101kl9r.html 一.java @override 报错处理 做项目的时候,同事那边电脑上编译通过的ja ...