为了解决同步阻塞I/O面临的一个链路需要一个线程处理的问题,后来有人对它的线程模型进行了优化,服务器端通过
一个线程池来处理多个客户端的请求接入,形成客户端个数M;线程池最大线程数N的比例关系,其中M可以远远大于N,
通过线程池可以灵活的调配线程资源,设置线程的最大值,防止由于海量并发接入导致线程耗尽系统资源。
伪异步IO的服务器端代码:
package com.panther.dong.netty.bio.fakeasychronousblockio;
import com.panther.dong.netty.bio.synchronousblockio.TimeServerHandler;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 伪异步IO
* Created by panther on 15-8-18.
*/
public class TimeServer {
public static void main(String[] args) {
int port = 8080;
if (args != null && args.length > 0) {
port = Integer.valueOf(args[0]);
}
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
System.out.println("The time server is start in port : " + port);
Socket socket;
TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(50, 10000); //创建io任务线程池
while (true) {
socket = serverSocket.accept();
singleExecutor.execute(new TimeServerHandler(socket));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
System.out.println("The time server close");
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
伪异步IO的主函数发生了变化。我们首先创建一个时间服务器处理类的线程池,当接收到新的客户端连接的时候,将请求
Socket封装成一个Task,然后调用线程池的execute方法执行,从而避免了每个请求接入都创建一个新的线程
线程池处理客户端接入的代码:
package com.panther.dong.netty.bio.fakeasychronousblockio;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池处理客户端的接入
* Created by panther on 15-8-18.
*/
public class TimeServerHandlerExecutePool {
private ExecutorService executor;
public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) {
executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maxPoolSize, 120L,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueSize));
}
public void execute(Runnable task) {
executor.execute(task);
}
}
因为线程池和消息队列都是有界的 ,因此,无论客户端并发连接数多大,它都不会导致线程个数过于膨胀或者内存溢出,
对于传统的线程模型,这是一种改进!!!!