Sub topic 13
Offloading heavy work with Isolate.run
Earlier chapters showed that await lets Dart's single thread wait for slow input and output without blocking. This chapter covers a different kind of slow work, where the program is busy computing rather than waiting. You will learn why await cannot help there, how Isolate.run moves the work to another thread of execution, and what the move costs.
This chapter assumes you are comfortable with the following:
Future,async, andawait, including how an exception inside an async function becomes an error in itsFuture.- The event loop model: one thread, an event queue, and a microtask queue.
- Closures, meaning anonymous functions that capture variables from the surrounding scope.
- Running a program with
dart run.
Why await does not help with CPU-bound work
await lets other code run only while the awaited operation is waiting on something outside your program, such as a timer, a socket, or a file read. The event loop is free during that wait.
A loop that sums a billion numbers is not waiting on anything. It occupies the one thread that runs your Dart code. While it runs, the event loop cannot take the next event or microtask. Timers fire late, and in a Flutter app the UI cannot draw frames. Marking the function async changes nothing, because an async function runs synchronously until its first await.
Future<int> slowButAsync() async {
var total = 0;
for (var i = 0; i < 1000000000; i++) {
total += i;
}
return total; // The whole loop ran with no chance for other events.
}The fix is to run the computation on a second thread of execution. Dart does this with isolates.
What an isolate is
An isolate is an independent worker with its own heap memory and its own event loop. Isolates do not share mutable memory, so Dart code has no data races and needs no locks. They can only communicate by sending messages.
- Each isolate has its own copy of every static and top-level variable. A global you set in the main isolate is not visible in another isolate.
- Each isolate runs one event loop, exactly as described in the event loop chapter.
- Isolates run in parallel on separate operating system threads, so heavy work in one does not delay events in another.
Using Isolate.run
Isolate.run takes a function, starts a new isolate, runs the function there, sends back the result, and shuts the isolate down. From your side it is a Future:
import 'dart:isolate';
int sumTo(int n) {
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
return total;
}
Future<void> main() async {
final ticker = Stream.periodic(
const Duration(milliseconds: 200),
(count) => count,
).listen((count) => print('main isolate is responsive: tick $count'));
final result = await Isolate.run(() => sumTo(1000000000));
print('sum: $result');
await ticker.cancel();
}The ticker prints while the sum is computed, because the main isolate's event loop is idle during the await. If you replace the Isolate.run line with final result = sumTo(1000000000);, the ticks stop until the sum finishes, because the computation blocks the only thread. The exact timing depends on your machine.
The signature is Future<R> Isolate.run<R>(FutureOr<R> Function() computation, {String? debugName}). The closure may also be async, and the isolate stays alive until its returned Future completes.
The life of one call
What crosses the isolate boundary
Because memory is not shared, data must be passed between isolates by value. Three things cross the boundary in a call to Isolate.run.
- The closure and everything it captures. The values it captures are copied into the new isolate.
- The result.
Isolate.runreturns it withIsolate.exit, which hands the object over without copying it. A large list or string comes back cheaply. - Errors. If the computation throws, the error is sent back and rethrown in the caller.
Copying has a cost that grows with the size of the data. Passing a 50 MB string into the worker copies 50 MB. If the data is large, consider reading or generating it inside the worker so that only a small input crosses the boundary.
Example: parsing a large JSON string
JSON decoding is CPU work, and a large payload can take long enough to drop frames in a Flutter app. This example moves the decoding into a worker:
import 'dart:convert';
import 'dart:isolate';
Future<List<int>> parseNumbers(String json) {
return Isolate.run(() {
final decoded = jsonDecode(json) as List<dynamic>;
return List<int>.from(decoded);
});
}
Future<void> main() async {
final json = jsonEncode(List<int>.generate(1000000, (i) => i));
final numbers = await parseNumbers(json);
print('parsed ${numbers.length} numbers, last is ${numbers.last}');
}The json string is copied into the worker, but the resulting list is transferred back without a copy.
What can be sent
Most Dart objects can be sent: numbers, strings, booleans, lists, maps, sets, plain class instances, and closures whose captured variables are themselves sendable. Objects tied to a specific isolate or to native resources cannot be sent. Examples are ReceivePort, Socket, and objects that hold native handles. Sending one throws an error at runtime, so a type that is not sendable usually shows up as a failure in testing, not at compile time.
Errors from the worker
An exception thrown inside the closure completes the returned Future with that error. You handle it as you would any other awaited failure:
import 'dart:isolate';
int parsePositive(String input) {
final value = int.parse(input);
if (value <= 0) {
throw RangeError.value(value, 'input', 'must be positive');
}
return value;
}
Future<void> main() async {
for (final input in ['12', 'abc', '-3']) {
try {
final value = await Isolate.run(() => parsePositive(input));
print('ok: $value');
} on FormatException catch (e) {
print('not a number: ${e.source}');
} on RangeError catch (e) {
print('out of range: ${e.message}');
} finally {
print('finished "$input"');
}
}
}The on clauses work because the error object itself is sent back. The stack trace refers to the worker's code, so the frames do not include the caller's line.
Gotchas
Capturing this
A closure created inside an instance method can capture this if it touches any field or method. The entire object is then copied into the worker, along with everything it references. If any of that is not sendable, the call fails. Copy the pieces you need into local variables first:
import 'dart:isolate';
class Report {
Report(this._values);
final List<int> _values;
Future<int> total() {
final values = _values; // Capture only the list, not the whole Report.
return Isolate.run(() => values.fold<int>(0, (sum, v) => sum + v));
}
}
Future<void> main() async {
final report = Report(List<int>.generate(1000, (i) => i));
print(await report.total());
}Spawning has a cost
Starting an isolate takes on the order of milliseconds, and copying data adds more. For work that takes well under a millisecond or two, Isolate.run is slower than doing the work inline. Measure before offloading small tasks.
I/O does not need an isolate
Network requests, file reads, and database calls already wait without blocking the event loop. Wrapping them in Isolate.run adds copying and startup cost and gains nothing. Use an isolate only when the time is spent computing.
Platform support
Isolate.run works on native platforms: the Dart VM, and Flutter on Android, iOS, desktop. It is not available on the web, where a program cannot spawn isolates. Flutter's compute function offers a similar call. On native platforms it uses an isolate, and on the web it runs the function on the main thread, so the work is not offloaded there.
When to use what
| Situation | Tool |
|---|---|
| Waiting on network, disk, or a timer | `await` on a `Future`, no isolate |
| Computation that takes under a millisecond or two | Run it inline |
| One-off heavy computation with a clear input and output | `Isolate.run` |
| Many repeated requests to the same worker, or a worker that must stay alive | `Isolate.spawn` with `SendPort` and `ReceivePort` |
| Heavy work on the web | Not available through `dart:isolate` |
A sound rule is to profile first. If a frame or request is slow and the time is spent in your own Dart loops, parsing, or encoding, move that piece into Isolate.run. If the time is spent waiting, fix the waiting instead.
Summary
awaitfrees the thread only while something external is pending. CPU-bound work still blocks the event loop.- An isolate has its own memory and event loop. Isolates communicate by sending messages and share no mutable state.
Isolate.runruns a closure in a short-lived isolate and returns aFutureof the result. Errors from the closure are rethrown in the caller.- Captured values are copied in, and the result moves back without copying. Avoid capturing
this. - Do not use it for I/O or for tiny tasks. It is unavailable on the web.
Exercise
A Flutter screen freezes for about 300 ms when it decodes a large JSON string with a function decodeAll(String json) declared Future<List<Item>> decodeAll(String json) async { ... }, which calls jsonDecode and then builds Item objects in a loop. A teammate says the async keyword should already prevent the freeze. Explain why it does not, and rewrite the function body so the freeze goes away.
Show answer
An async function runs synchronously until its first await. The function has no await around the decoding, so jsonDecode and the loop run on the main isolate and block its event loop and frame drawing. The work is CPU-bound and never waits on anything external. Move it into a worker:
Future<List<Item>> decodeAll(String json) {
return Isolate.run(() {
final raw = jsonDecode(json) as List<dynamic>;
return [for (final entry in raw) Item.fromJson(entry as Map<String, dynamic>)];
});
}
The json string is copied into the worker, and the resulting list is returned without a copy. The closure uses only the local json variable, so it does not capture this.
Exercise
You call Isolate.run(() => compute()) inside a method, and compute reads a top-level variable apiBaseUrl that the main isolate assigned at startup. The worker sees the wrong value. Why, and what is the fix?
Show answer
Each isolate has its own copy of top-level and static variables, initialized from their declarations. The assignment in the main isolate is not visible in the worker. The fix is to read apiBaseUrl into a local variable before the call, then use that local inside the closure, or pass it as an argument to the function you run, so the value is copied into the worker.