Patterncore
Reactor
Also called reactor pattern, dispatcher, notifier.
A reactor waits for events on many handles in one thread and calls the handler that is registered for each handle, so one thread serves many connections.
- Family
- concurrency
- Intent
- Demultiplex the events that arrive on many handles and dispatch each event to the handler that is registered for its handle, with no thread for each connection.
- Also called
- Dispatcher, Notifier
Intent
The Reactor design pattern handles service requests that are delivered concurrently to an application by one or more clients.1 It is also known as Dispatcher and Notifier.1 The pattern's key component is an event loop, running in a single thread or process, which demultiplexes incoming requests and dispatches them to the correct request handler.2
Problem
A server has many connections, and on each connection a request can arrive at any time. An iterative server reads one request from start to finish in each turn of its loop, and it will fall behind once it receives multiple requests in quick succession.2 A thread for each connection solves the wait, but each new thread or process imposes overhead costs in memory and processing time.2 Both approaches also tightly couple the general demultiplexer with specific request handlers.2
Solution
The paper names five participants.1
- Handle. It identifies a resource that is managed by an OS, such as a network connection, an open file or a timer.1
- Synchronous Event Demultiplexer. It blocks awaiting events to occur on a set of Handles, and it returns when it is possible to initiate an operation on a Handle without blocking.1 A common demultiplexer for I/O events is
select.1 - Initiation Dispatcher. It keeps a table of event handlers, with
register_handlerandremove_handler, and itshandle_eventsloop calls the demultiplexer.1 - Event Handler. It declares the hook method
handle_event.1 - Concrete Event Handler. It gives the application code for one kind of event.
register_handler(h)
handler ------------------> Initiation Dispatcher
^ | handle_events():
| | ready = select(handles)
| handle_event(data) | for h in ready:
+---------------------------+ handlers[h].handle_event()
The dispatcher calls the handlers one at a time in its thread. The Initiation Dispatcher calls back to the handle event hook method of the Event Handler.1 That is an inversion of control: the framework, not the handler, decides when the handler runs.
Example
The example files show one program in each language. A list of ready events takes the place of select, so the output is the same on each run. An acceptor handler is registered for the handle listener. Each event on it registers a new echo handler for a new connection. An empty message closes the connection and removes its handler. The program prints:
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
class Reactor:
def __init__(self):
self.handlers = {}
def register(self, handle, handler):
self.handlers[handle] = handler
def remove(self, handle):
del self.handlers[handle]
def run(self, ready):
# ready stands in for select: (handle, data) pairs in arrival order
for handle, data in ready:
self.handlers[handle](handle, data)
reactor = Reactor()
def echo(handle, data):
if data:
print(f"{handle}: {data}")
else:
print("close", handle)
reactor.remove(handle)
def acceptor(handle, new_handle):
print("accept", new_handle)
reactor.register(new_handle, echo)
reactor.register("listener", acceptor)
reactor.run([
("listener", "conn-1"), ("listener", "conn-2"),
("conn-1", "hello"), ("conn-2", "hi"),
("conn-1", ""), ("conn-2", ""),
])
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: native. A handler is a function, so the table of handlers is a dictionary from handle to function. The
selectorsmodule gives the real demultiplexer.
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using Handler = std::function<void(const std::string&, const std::string&)>;
std::map<std::string, Handler> handlers;
void echo(const std::string& handle, const std::string& data) {
if (!data.empty()) {
std::cout << handle << ": " << data << "\n";
} else {
std::cout << "close " << handle << "\n";
handlers.erase(handle);
}
}
int main() {
handlers["listener"] = [](const std::string&, const std::string& newHandle) {
std::cout << "accept " << newHandle << "\n";
handlers[newHandle] = echo;
};
// ready stands in for select: handle and data pairs in arrival order
std::vector<std::pair<std::string, std::string>> ready{
{"listener", "conn-1"}, {"listener", "conn-2"},
{"conn-1", "hello"}, {"conn-2", "hi"},
{"conn-1", ""}, {"conn-2", ""}};
for (const auto& [handle, data] : ready) {
Handler handler = handlers.at(handle); // a copy, because echo can erase its entry
handler(handle, data);
}
}
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: idiom. The handler table maps handles to
std::functionvalues. The dispatcher copies the handler before the call, because a handler that removes itself would otherwise destroy the function that is running.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
public class Main {
static final Map<String, BiConsumer<String, String>> handlers = new HashMap<>();
static void echo(String handle, String data) {
if (!data.isEmpty()) {
System.out.println(handle + ": " + data);
} else {
System.out.println("close " + handle);
handlers.remove(handle);
}
}
public static void main(String[] args) {
handlers.put("listener", (handle, newHandle) -> {
System.out.println("accept " + newHandle);
handlers.put(newHandle, Main::echo);
});
// ready stands in for select: handle and data pairs in arrival order
List<String[]> ready = List.of(
new String[] {"listener", "conn-1"}, new String[] {"listener", "conn-2"},
new String[] {"conn-1", "hello"}, new String[] {"conn-2", "hi"},
new String[] {"conn-1", ""}, new String[] {"conn-2", ""});
for (String[] event : ready) {
handlers.get(event[0]).accept(event[0], event[1]);
}
}
}
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: idiom. The handler table maps handles to
BiConsumerlambdas, and a method reference gives the echo handler.
using System;
using System.Collections.Generic;
static class Program
{
static readonly Dictionary<string, Action<string, string>> Handlers = new();
static void Echo(string handle, string data)
{
if (data.Length > 0)
{
Console.WriteLine($"{handle}: {data}");
}
else
{
Console.WriteLine($"close {handle}");
Handlers.Remove(handle);
}
}
static void Main()
{
Handlers["listener"] = (handle, newHandle) =>
{
Console.WriteLine($"accept {newHandle}");
Handlers[newHandle] = Echo;
};
// ready stands in for select: handle and data pairs in arrival order
var ready = new (string Handle, string Data)[]
{
("listener", "conn-1"), ("listener", "conn-2"),
("conn-1", "hello"), ("conn-2", "hi"),
("conn-1", ""), ("conn-2", ""),
};
foreach (var (handle, data) in ready)
{
Handlers[handle](handle, data);
}
}
}
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: idiom. The handler table maps handles to
Action<string, string>delegates, and a tuple array gives the ready events.
class Reactor {
constructor() {
this.handlers = new Map();
}
register(handle, handler) {
this.handlers.set(handle, handler);
}
remove(handle) {
this.handlers.delete(handle);
}
run(ready) {
// ready stands in for select: [handle, data] pairs in arrival order
for (const [handle, data] of ready) {
this.handlers.get(handle)(handle, data);
}
}
}
const reactor = new Reactor();
function echo(handle, data) {
if (data) {
console.log(`${handle}: ${data}`);
} else {
console.log("close", handle);
reactor.remove(handle);
}
}
reactor.register("listener", (handle, newHandle) => {
console.log("accept", newHandle);
reactor.register(newHandle, echo);
});
reactor.run([
["listener", "conn-1"], ["listener", "conn-2"],
["conn-1", "hello"], ["conn-2", "hi"],
["conn-1", ""], ["conn-2", ""],
]);
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: native. A handler is a function value in a
Map.
type Handler = (handle: string, data: string) => void;
class Reactor {
private handlers = new Map<string, Handler>();
register(handle: string, handler: Handler): void {
this.handlers.set(handle, handler);
}
remove(handle: string): void {
this.handlers.delete(handle);
}
run(ready: Array<[string, string]>): void {
// ready stands in for select: [handle, data] pairs in arrival order
for (const [handle, data] of ready) {
const handler = this.handlers.get(handle);
if (handler) handler(handle, data);
}
}
}
const reactor = new Reactor();
const echo: Handler = (handle, data) => {
if (data) {
console.log(`${handle}: ${data}`);
} else {
console.log("close", handle);
reactor.remove(handle);
}
};
reactor.register("listener", (_handle, newHandle) => {
console.log("accept", newHandle);
reactor.register(newHandle, echo);
});
reactor.run([
["listener", "conn-1"], ["listener", "conn-2"],
["conn-1", "hello"], ["conn-2", "hi"],
["conn-1", ""], ["conn-2", ""],
]);
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: native. The type
Handleris the hook method as a function type.Map.getcan returnundefined, so the dispatcher checks the handler before it calls it.
package main
import "fmt"
type Handler func(handle, data string)
var handlers = map[string]Handler{}
func echo(handle, data string) {
if data != "" {
fmt.Printf("%s: %s\n", handle, data)
} else {
fmt.Println("close", handle)
delete(handlers, handle)
}
}
func main() {
handlers["listener"] = func(_, newHandle string) {
fmt.Println("accept", newHandle)
handlers[newHandle] = echo
}
// ready stands in for select: handle and data pairs in arrival order
ready := [][2]string{
{"listener", "conn-1"}, {"listener", "conn-2"},
{"conn-1", "hello"}, {"conn-2", "hi"},
{"conn-1", ""}, {"conn-2", ""},
}
for _, event := range ready {
handlers[event[0]](event[0], event[1])
}
}
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: idiom. The handler table is a map from handle to function value.
use std::collections::HashMap;
enum Handler {
Acceptor,
Echo,
}
fn main() {
let mut handlers: HashMap<String, Handler> = HashMap::new();
handlers.insert("listener".to_string(), Handler::Acceptor);
// ready stands in for select: handle and data pairs in arrival order
let ready = [
("listener", "conn-1"), ("listener", "conn-2"),
("conn-1", "hello"), ("conn-2", "hi"),
("conn-1", ""), ("conn-2", ""),
];
for (handle, data) in ready {
match handlers.get(handle) {
Some(Handler::Acceptor) => {
println!("accept {}", data);
handlers.insert(data.to_string(), Handler::Echo);
}
Some(Handler::Echo) if !data.is_empty() => println!("{}: {}", handle, data),
Some(Handler::Echo) => {
println!("close {}", handle);
handlers.remove(handle);
}
None => {}
}
}
}
accept conn-1
accept conn-2
conn-1: hello
conn-2: hi
close conn-1
close conn-2
- Verdict: idiom. The handlers are the variants of an enum, and the dispatcher matches on them. A closure that changes the table it is stored in would need shared mutable state, so the enum keeps the borrow simple.
Consequences
Benefits:1
- Separation of concerns. The Reactor pattern decouples application-independent demultiplexing and dispatching mechanisms from application-specific hook method functionality.1
- Modularity and reuse. In the paper's logging server, there are two separate classes: one for establishing connections and another for receiving and processing logging records.1
- Portability. The Initiation Dispatcher's interface can be reused independently of the OS system calls that perform event demultiplexing.1
- Coarse-grained concurrency control. Serialization at the Initiation Dispatcher level often eliminates the need for more complicated synchronization or locking within an application process.1
Liabilities:1
- Restricted applicability. The Reactor pattern can only be applied efficiently if the OS supports Handles.1
- Non-preemptive. An Event Handler should not perform blocking I/O on an individual Handle since this will block the entire process.1
- Hard to debug. The inverted flow of control oscillates between the framework infrastructure and the method callbacks on application-specific handlers.1
The second liability is the common mistake. Here the first handler sleeps, and the second handler, which is ready at the same time, must wait:
This code runs but gives a wrong answer on purpose.
import time
start = time.monotonic()
def slow(data):
time.sleep(0.2) # blocking work inside a handler
print("slow:", data)
def fast(data):
waited = time.monotonic() - start
print("fast:", data, "| waited 0.2 s or more:", waited >= 0.2)
handlers = {"a": slow, "b": fast}
for handle, data in [("a", "report"), ("b", "ping")]: # both ready together
handlers[handle](data)
slow: report
fast: ping | waited 0.2 s or more: True
The fix is to give long work to another thread or process, for example with the Active Object pattern.1
When not to use it
- The work for each request is long and uses the CPU. One thread then serves the requests one after the other.
- There are few connections, and a thread for each one is simpler to write and to read.
- The platform has no demultiplexer for the resources, so the reactor must be emulated with threads.1
Variants and related patterns
- Handlers in a thread pool. One basic modification is to invoke event handlers in their own threads for more concurrency.2
- Multireactor. Replicated dispatchers run concurrently, and the dispatcher count matches the available CPU cores of the underlying hardware.2
- Proactor. It dispatches the completion of asynchronous operations, not readiness. It still makes use of a reactor subcomponent.2
- Event handling patterns. POSA2 puts Reactor with Proactor, Asynchronous Completion Token and Acceptor-Connector.3
The Python module selectors allows high-level and efficient I/O multiplexing, built upon the select module primitives.4 This reactor waits on two real sockets, and the data of each registration is its handler:
import selectors
import socket
sel = selectors.DefaultSelector()
def make_handler(name):
def on_readable(sock):
data = sock.recv(100)
if data:
print(name, "read", data.decode())
else:
print(name, "closed")
sel.unregister(sock)
sock.close()
return on_readable
ends = {}
for name in ["one", "two"]:
client, server = socket.socketpair()
server.setblocking(False)
sel.register(server, selectors.EVENT_READ, make_handler(name))
ends[name] = client
def dispatch_once():
for key, _ in sel.select(timeout=1):
key.data(key.fileobj) # call the registered handler
for name, message in [("one", b"hello"), ("two", b"hi")]:
ends[name].sendall(message)
dispatch_once()
for name in ["one", "two"]:
ends[name].close()
dispatch_once()
one read hello
two read hi
one closed
two closed
Known uses
- InterViews. The InterViews window system implements the pattern under the name Dispatcher.1
- ACE. The ACE framework uses the Reactor pattern as its central event demultiplexer and dispatcher.1
- libuv. libuv was originally written for Node.js.5 Its I/O loop is meant to be tied to a single thread, and it polls non-blocking sockets with epoll on Linux, kqueue on OSX and other BSDs, event ports on SunOS and IOCP on Windows.5
- Python. The
selectorsmodule has concrete implementations such asKqueueSelectorandEpollSelector.4
References
- Douglas C. Schmidt, Reactor, An Object Behavioral Pattern for Demultiplexing and Dispatching Handles for Synchronous Events, Intent; Also Known As; Structure; Known Uses; Consequences
- Reactor pattern, Wikipedia, Introduction; Overview; Variants
- Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Table of Contents, 3 Event Handling Patterns
- selectors, High-level I/O multiplexing, Python documentation, Introduction
- Design overview, libuv documentation, Design overview; The I/O loop
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag VRY55J Edit this page History Report an error Markdown