reactor和proactor模式的比较

时间:2022-04-19 05:32:15

在研究Java AIO的时候理解到reactor和proactor模式,顺便研究了一下。

这里面会提到blokcing/non-blocking, synchronous/asynchronous的对比,要仔细体会才行。

 

如果实现一个高性能的服务器端,比如web server,有以下几种方式:

详细的可以参考http://www.cs.wustl.edu/~schmidt/PDF/Reactor1-93.pdf

 

1、Non-blocking I/O solution

One method for handling I/O on multiple descriptors involves the use of "polling." polling operates by cycling through a set of open descriptors, checking each one for pending I/O activity.

 

The primary disadvantage with polling is that it consumes excessive CPU cycles by making unnecessary system calls while "busy-waiting". For instance, if input occurs only intermittently on the I/O descriptors, the server process will repeatedly and superfluously poll descriptors that do not have any pending logging records. On the other hand, if I/O is continuously received up all descriptors, this approach may be reasonable. In addition, an advantage with polling is that it is portable accross OS platforms.

 

2、Multi-Process Solution - master/slave模式

有一个master进程负责监听client请求,然后对于每个请求调用fork方法创建一个单独的进程去处理。

 

 

3、Multi-threaded solution

和2类似,只不过将process换成了更轻量级的thread

 

4、The Event Demultiplexing Solution

主要是用到了操作系统的事件多路分用(event demultiplexing)功能:通过调用select和poll。这一类里根据实现的不同又分为几类:

 

4.1 select-based 

4.2 poll-based

以上两种存在着以下一些缺点:

-> Complicated and Error-Prone Interfaces

-> Low-Level Interfaces

-> Non-Portable Interfaces

-> Non-Extensible Interfaces

 

为了解决这些问题,我们在更高层面引入了模式,把这些底层的信息屏蔽掉了,使得更易于使用。

 

4.3 reactive event dispatching model

 

4.4 proactive event dispatching model

Java AIO的实现者Alan Bateman解释以上两种模式的区别是:

proactive:

-> Initiate non-blocking I/O operation

-> Notification when I/O completes

-> Proactor pattern

 

reactive:

-> notification when channel ready for I/O (Selector)

-> perform non-blocking I/O operation

-> Reactor pattern

 

说实话,还不是很能理解其中的奥秘。