Sub topic 10
Building a long-lived worker
Isolate.run starts a new isolate, runs one closure, and throws the isolate away. That suits one-off jobs. If your app sends many jobs, you pay the startup cost each time, and any state the worker built is lost. A long-lived worker isolate starts once, keeps running, and handles requests as they arrive.
This chapter assumes you know Isolate.run, what can be sent in a message, and the basics of Future, Completer, and Stream. It builds on Isolate.spawn, ReceivePort, and SendPort from the previous chapter.
When a long-lived worker is the right tool
| Situation | Better choice |
|---|---|
| One expensive job, such as parsing a single file | `Isolate.run` |
| Many small or medium jobs over time | Long-lived worker |
| Expensive setup you want to reuse (a parsed index, a loaded model, an open database) | Long-lived worker |
| Streaming progress or results back while work continues | Long-lived worker |
Spawning an isolate costs time and memory. If each job runs for milliseconds, a spawn per job can cost more than the job. A worker spreads that cost over every job it handles.
The shape of the conversation
Isolates share no memory, so a worker and its caller talk through ports. A ReceivePort is the receiving end and a SendPort is a handle for sending to it. Each isolate needs its own ReceivePort. The usual handshake has three steps:
- The main isolate creates a
ReceivePortand passes itsSendPortto the new isolate as the spawn argument. - The worker creates its own
ReceivePortand sends that port'sSendPortback. - Both sides now hold a
SendPortfor the other, and requests and responses flow in both directions.
A minimal worker
This version shows the protocol with nothing around it. The worker sends its port back, handles (id, n) records, and stops when it receives null.
import 'dart:isolate';
int _sumTo(int n) {
var s = 0;
for (var i = 1; i <= n; i++) {
s += i;
}
return s;
}
void _worker(SendPort toMain) {
final commands = ReceivePort();
toMain.send(commands.sendPort);
commands.listen((message) {
if (message == null) {
commands.close();
return;
}
final (id, n) = message as (int, int);
toMain.send((id, _sumTo(n)));
});
}
Future<void> main() async {
final fromWorker = ReceivePort();
await Isolate.spawn(_worker, fromWorker.sendPort);
final events = StreamIterator<dynamic>(fromWorker);
await events.moveNext();
final toWorker = events.current as SendPort;
toWorker.send((1, 100000000));
await events.moveNext();
final (id, result) = events.current as (int, int);
print('job $id -> $result');
toWorker.send(null); // ask the worker to stop
fromWorker.close();
}Four details matter here:
- The entry function
_workeris top-level. It receives one argument, theSendPort, and nothing else from the spawning isolate. - The messages are records of ints. Records are sendable when their fields are sendable.
nullis the shutdown signal. AReceivePortkeeps its isolate alive, so the worker must close it to let the isolate exit.- The main isolate must also close
fromWorker. An openReceivePortcan keep a Dart program from exiting.
Wrapping the protocol in a class
The minimal version works for one request. With several requests in flight, the caller needs to match each response to the request that caused it. The standard pattern is a request id plus a map of Completers. The class below hides the ports behind an ordinary Future-returning method.
import 'dart:async';
import 'dart:isolate';
int _sumTo(int n) {
if (n < 0) throw ArgumentError('n must be non-negative');
var s = 0;
for (var i = 1; i <= n; i++) {
s += i;
}
return s;
}
void _workerMain(SendPort toMain) {
final commands = ReceivePort();
toMain.send(commands.sendPort);
commands.listen((message) {
if (message == null) {
commands.close();
return;
}
final (id, n) = message as (int, int);
try {
toMain.send((id, _sumTo(n), null));
} catch (e) {
toMain.send((id, null, e.toString()));
}
});
}
class SumWorker {
SumWorker._(this._fromWorker);
final ReceivePort _fromWorker;
late final SendPort _toWorker;
final _pending = <int, Completer<int>>{};
var _nextId = 0;
var _closed = false;
static Future<SumWorker> start() async {
final fromWorker = ReceivePort();
final worker = SumWorker._(fromWorker);
final ready = Completer<SendPort>();
fromWorker.listen((message) {
if (message is SendPort) {
ready.complete(message);
} else if (message == null) {
// Sent by the onExit port when the worker isolate ends.
worker._failAll(StateError('Worker isolate exited'));
} else {
worker._onResponse(message as (int, int?, String?));
}
});
await Isolate.spawn(
_workerMain,
fromWorker.sendPort,
onExit: fromWorker.sendPort,
);
worker._toWorker = await ready.future;
return worker;
}
Future<int> sumTo(int n) {
if (_closed) throw StateError('Worker is closed');
final id = _nextId++;
final completer = Completer<int>();
_pending[id] = completer;
_toWorker.send((id, n));
return completer.future;
}
void _onResponse((int, int?, String?) message) {
final (id, result, error) = message;
final completer = _pending.remove(id);
if (completer == null) return;
if (error != null) {
completer.completeError(Exception(error));
} else {
completer.complete(result);
}
}
void _failAll(Object error) {
for (final completer in _pending.values) {
completer.completeError(error);
}
_pending.clear();
}
void close() {
if (_closed) return;
_closed = true;
_toWorker.send(null);
_fromWorker.close();
_failAll(StateError('Worker closed'));
}
}
Future<void> main() async {
final worker = await SumWorker.start();
try {
final results = await Future.wait([
worker.sumTo(10),
worker.sumTo(100000000),
worker.sumTo(5),
]);
print(results); // [55, 5000000050000000, 15]
await worker.sumTo(-1);
} catch (e) {
print('failed: $e');
} finally {
worker.close();
}
}This code runs on native platforms. On the web, Isolate.spawn is not available (see the platform chapter).
How the pieces fit
- One listener, three message kinds. A
ReceivePortis a single-subscription stream, so you can attach only one listener. The first message is the worker'sSendPort. Later messages are response records. Anullis the exit notification. onExit. PassingonExit: fromWorker.sendPortmakes the runtime sendnullto that port when the worker isolate ends for any reason. If the worker dies,_failAllcompletes every waiting future with an error. Without it, those futures would never complete.- Ids and completers. Each request gets a unique id. The worker echoes the id back, and
_onResponseuses it to find the rightCompleter. Responses can therefore arrive in any order from the caller's point of view. - Errors as data. An exception thrown inside the worker's listener does not reach the caller's
try/catch. The worker catches it, converts it to aString, and sends it as part of the response. The caller rebuilds an exception from that string. This keeps the message sendable and the worker alive.
Failure modes to plan for
- Uncaught errors in the worker. By default an uncaught error is fatal and ends the isolate.
onExitlets you notice that. To also get the error and stack trace, passonErrorwith a port. It receives a two-element list of strings. - Requests lost at shutdown.
close()above fails every pending request immediately. If you want in-flight work to finish, wait for_pendingto empty before sendingnull. - Unsendable payloads. Sending a closure, a
ReceivePort, or an object holding native resources throws atsendtime. Keep protocol messages to primitives, lists, maps, records, andSendPorts. - Unbounded queues. Messages queue in the worker's port without limit. If the producer is faster than the worker, memory grows. Cap the number of pending requests, or reject new ones when
_pendingis large. - Leaked workers. Forgetting
close()leaves the isolate running. Tie its lifetime to an owner, for example create it in aState.initStateand close it indispose.
Keeping state inside the worker
A long-lived worker can hold state that the main isolate never sees. The worker's top-level variables and its closure locals belong to its own heap. For example, a worker can parse a large file once, keep the index in a local variable, and answer many search requests without copying the index back and forth. Only the small queries and results cross the isolate boundary. This is often the strongest reason to choose a worker over repeated Isolate.run calls.
Exercise
In the SumWorker class, why does start() call fromWorker.listen before it awaits ready.future, and what would go wrong if the first message were consumed with fromWorker.first and a second listen were added afterwards?
Show answer
The worker sends its SendPort as the first message, so a listener must already be attached to receive it. A ReceivePort is a single-subscription stream. Calling first subscribes and then cancels the subscription, which closes the port, so a later listen would fail or never receive responses. Using one listener that branches on the message type (SendPort, null, or response record) avoids both problems.
Exercise
A caller sends worker.sumTo(3000000000) and then worker.sumTo(2). Which future completes first, and how would you make the second request finish quickly without changing the worker's code?
Show answer
The first future completes first, because the worker processes messages one at a time and sumTo(2) waits behind the long job. To avoid the wait, start a second worker and send the short request to it, or send long jobs to one worker and short jobs to another.