java并发之并行WebServer和Executor框架
我们先来一个简单的串行单线程WebServer
public class WebServer {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(80);
while (true) {
Socket connection = socket.accept();
handleRequest(connection);
}
}
private static void handleRequest(Socket connection) {
System.out.println("访问");
}
}
那么现在
如果我们访问80端口,就会调用socket的accept方法建立连接
并且执行handleRequest,执行一句话
这个WebServer理论上是正确的
但是它的性能肯定是非常差的
是单线程的,所以每次只能执行一个请求
我们做一点简单的修改
将这个WebServer改成并行的多线程服务器
public class WebServer {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection = socket.accept();
Runnable task = new Runnable() {
@Override
public void run() {
handleRequest(connection);
}
};
new Thread(task).start();
}
}
private static void handleRequest(Socket connection) {
System.out.println("访问");
}
}
我们看见
每次收到请求的时候,
就会开启一个新的线程来执行handleRequest方法
这样就变成了并发的多线程服务器
但是
但是
但是
不要这么做
不要这么做
不要这么做
重要的事情说三遍
因为
我们发现,这样的服务器
实际上,是无限制地开启新的线程,会有很多问题
1.线程生命周期的开销非常高 (也就是会反复地非常多次地创建,销毁线程)
2.资源消耗大 (大量消耗系统资源,尤其是内存,CPU处理速度有限,大量创建线程占据内存)
3.稳定性 (线程数和内存有限制,会内存溢出)
然后我们来说Executor框架
线程池简化了线程的管理工作
java.util.concurrent包就提供了一种灵活的线程池实现
也就是Executor框架的一部分
我们来看一下Executor接口
public interface Executor {
/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the {@code Executor} implementation.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
}
虽然Executor是个简单的接口
但它就是强大的异步任务执行框架的基础
这个框架能支持多种不同类型的任务执行策略
现在我们来用Executor再来修改一下刚才的WebServer
public class WebServer {
private static final int THREADSNUMBER = 100;
private static final Executor executor = Executors.newFixedThreadPool(THREADSNUMBER);
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection = socket.accept();
Runnable task = new Runnable() {
@Override
public void run() {
handleRequest(connection);
}
};
executor.execute(task);
}
}
private static void handleRequest(Socket connection) {
System.out.println("访问");
}
}
和刚刚的多线程服务器很相似
但是加入了Executor做线程管理