Explain it simply
Explain it simply
Imagine one cook in a tiny kitchen doing everything: chopping vegetables, serving guests, answering the phone. If a huge order of vegetables arrives and the cook chops for ten minutes straight, nobody gets served and the phone rings out. That cook is the main isolate, and the chopping is CPU work.
An isolate is a second cook with a separate kitchen: their own counter, their own tools, their own phone. You pass written notes through a hatch, and they pass the finished dish back. Because the two kitchens share nothing, both cooks can work at the same time, and they can never grab the same knife.
Problem → Why → Solution
The problem: a busy loop delays the timer
In the program below a timer is set for 10 ms. The program then does 100 ms of synchronous work, a stand-in for decoding a large file or resizing an image. The timer callback cannot interrupt that work, because an isolate runs one piece of Dart code at a time.
Only when the loop is free again does the timer fire, so it runs at least 100 ms after it was scheduled, not 10. In a Flutter app the same effect shows up as dropped frames: drawing waits behind your computation, and the screen freezes.
import 'dart:async';
void main() {
final clock = Stopwatch()..start();
Timer(Duration(milliseconds: 10), () {
print('timer ran after at least 100 ms: ${clock.elapsedMilliseconds >= 100}');
});
while (clock.elapsedMilliseconds < 100) {} // busy work blocks the event loop
print('busy work finished');
}Why doesn't async/await help?
async and await let a function wait without blocking, but they do not move computation anywhere else. A busy loop blocks the event loop no matter which function contains it. To use another CPU core you need another isolate.
Core concept: private memory and messages
An isolate is an independent worker with its own memory heap, its own event loop and its own microtask queue. Every Dart program starts with one main isolate. Isolates do not share mutable state, so there are no locks and no data races; in exchange they have to communicate by messages.
Messages are sent with SendPort.send and received through a ReceivePort. The object you send is normally copied, so changes made on the receiving side are invisible to the sender. Your own class instances can be copied as well, but objects that hold native resources, such as a ReceivePort, cannot be sent.
| The job | The tool |
|---|---|
| Waiting for network or file I/O | await (no isolate needed) |
| One CPU-heavy job | Isolate.run(() => ...) |
| Several independent CPU jobs | Future.wait over Isolate.run |
| A worker that gets many messages | Isolate.spawn plus ports |
Isolate.run(() => work) starts a new isolate, runs the closure, hands the result back as a Future and shuts the isolate down. The closure and everything it captures are copied across. If the closure throws, the error is rethrown at the caller's await. Isolate.spawn(entryPoint, message) is for a long-lived worker: the entry point is a top-level or static function, and you keep talking to it through ports. The new isolate also gets its own copy of every top-level variable.
An isolate is not free. Starting one and copying data both cost time, so it does not pay off for work that takes only a few milliseconds. Use it for CPU-bound work such as decoding a large JSON document, processing an image or computing hashes. Do not use it for waiting on a server; await is simpler and enough.
- One isolate = its own memory and loop
- Closures and messages are copied across
- Isolate.run: closure in, result out
- Ports are the only door between isolates
Because nothing is shared, a change made on one side is never visible on the other; keep that in mind whenever you design a message.
General pattern
// one-off job: the closure runs in a new isolate
final result = await Isolate.run(() => heavyWork(input));
// long-lived worker: talk through ports
final inbox = ReceivePort();
await Isolate.spawn(entryPoint, inbox.sendPort);
void entryPoint(SendPort toParent) {
toParent.send(message);
}Isolate.run runs one closure in a fresh isolate and returns the result. Isolate.spawn takes an entry-point function plus a SendPort and keeps the worker alive for more messages.
Counting primes in two isolates
countPrimes(from, to) is CPU work: it counts the primes in one range. The program splits the range up to 1,000,000 into two halves and runs both with Isolate.run at the same time. Meanwhile the main isolate runs a timer that ticks every 10 ms.
The exact tick count depends on the machine, so it is not printed; the program only checks whether any tick happened. All printing happens from one place after both isolates finish, so the output is the same on every run.
import 'dart:async';
import 'dart:isolate';
int countPrimes(int from, int to) {
var count = 0;
for (var n = from < 2 ? 2 : from; n < to; n++) {
var isPrime = true;
for (var d = 2; d * d <= n; d++) {
if (n % d == 0) {
isPrime = false;
break;
}
}
if (isPrime) count++;
}
return count;
}
Future<void> main() async {
var ticks = 0;
final heartbeat = Timer.periodic(Duration(milliseconds: 10), (_) => ticks++);
final halves = await Future.wait([
Isolate.run(() => countPrimes(2, 500000)),
Isolate.run(() => countPrimes(500000, 1000000)),
]);
heartbeat.cancel();
print('primes in [2, 500000): ${halves[0]}');
print('primes in [500000, 1000000): ${halves[1]}');
print('total: ${halves[0] + halves[1]}');
print('event loop kept ticking: ${ticks > 0}');
}Code breakdown
- Pure CPU work
int countPrimes(int from, int to) {This function does no I/O and awaits nothing; it only computes. Run on the main isolate it would block the event loop.
- A heartbeat on the main isolate
final heartbeat = Timer.periodic(Duration(milliseconds: 10), (_) => ticks++);The timer lives on the main isolate's event loop. While that loop stays free, ticks keeps growing, so the counter is evidence that the loop was never blocked.
- One isolate per range
Isolate.run(() => countPrimes(2, 500000)),The closure runs in a new isolate. It captures only two ints, so almost nothing needs copying, and the int result comes back as a Future.
- Waiting for both
final halves = await Future.wait([Both Isolate.run calls start before the await, so they can run at the same time. The result list keeps the order in which the Futures were given.
- Stopping the timer
heartbeat.cancel();A periodic timer that is never cancelled keeps the event loop alive and the program never exits. Cancel it as soon as the work is done.
- A deterministic check
print('event loop kept ticking: ${ticks > 0}');Checking ticks > 0 gives the same output on a fast or a slow machine, because the exact tick count is never printed.
primes in [2, 500000): 41538
primes in [500000, 1000000): 36960
total: 78498
event loop kept ticking: true- The caller calls Isolate.run(closure)
- A new isolate gets a copy of the closure and its data
- The closure runs on another core; caller loop is free
- The result is sent back and the isolate exits
The closure succeeds
The caller's Future completes with the result.
The closure throws
The same error is rethrown at the caller's await.
Nothing is shared
The closure below adds 100 to the top-level variable counter and appends an item to the names list. Both changes happen on the copies that live inside the new isolate. When main looks at its own counter and names afterwards, nothing has changed.
import 'dart:isolate';
int counter = 0; // every isolate gets its own copy of this variable
Future<void> main() async {
final names = ['ada'];
final inside = await Isolate.run(() {
counter += 100;
names.add('grace'); // changes the copy that lives inside the new isolate
return (counter, names.length);
});
print('inside the isolate: $inside');
print('main sees: counter=$counter, names=$names');
}inside the isolate: (100, 2)
main sees: counter=0, names=[ada]Objects that cannot be sent
If a closure captures an object that holds a native resource, such as a ReceivePort, running it fails with an ArgumentError whose message contains 'Illegal argument in isolate message: object is unsendable'. Capture only the data you need (numbers, strings, lists), never UI objects or ports.
A worker you keep talking to
Isolate.run shuts the isolate down after one job. To send many messages, keep a worker alive with Isolate.spawn and talk through two ports. First main creates a ReceivePort and hands its sendPort to the worker. The worker creates its own ReceivePort and sends its sendPort back as the first message, a handshake. After that main sends jobs to the worker.
In the code below there is one worker and each message is awaited before the next, so the order cannot change. When the worker receives 'stop' it closes its port, and main cancels its subscription so its own port closes and the program can end.
import 'dart:async';
import 'dart:isolate';
void squareWorker(SendPort toParent) {
final inbox = ReceivePort();
toParent.send(inbox.sendPort); // tell the parent where to send jobs
inbox.listen((message) {
if (message == 'stop') {
inbox.close();
toParent.send('stopped');
} else {
toParent.send(message * message);
}
});
}
Future<void> main() async {
final fromWorker = ReceivePort();
await Isolate.spawn(squareWorker, fromWorker.sendPort);
final replies = StreamIterator(fromWorker);
await replies.moveNext();
final toWorker = replies.current as SendPort;
final results = <int>[];
for (final n in [3, 4, 5]) {
toWorker.send(n);
await replies.moveNext();
results.add(replies.current as int);
}
toWorker.send('stop');
await replies.moveNext();
print('squares: $results, then ${replies.current}');
await replies.cancel();
}squares: [9, 16, 25], then stoppedErrors cross the boundary
If the closure inside Isolate.run throws, the error is sent back to the caller and rethrown at the await, so ordinary try/on/catch can handle it. A failure inside one isolate does not take the main isolate down by itself.
import 'dart:isolate';
int parseAll(List<String> items) => items.map(int.parse).fold(0, (a, b) => a + b);
Future<void> main() async {
final ok = await Isolate.run(() => parseAll(['1', '2', '3']));
print('ok: $ok');
try {
await Isolate.run(() => parseAll(['1', 'two']));
} on FormatException catch (e) {
print('rethrown here: ${e.message}');
}
}ok: 6
rethrown here: Invalid radix-10 numberIn real projects
In real projects
In a Flutter app, decoding a JSON document that is megabytes in size, resizing or filtering an image, and encrypting or hashing data are sent to an isolate. Without that, frames drop and scrolling stutters. Flutter's compute() helper does a similar job of running a function in a separate isolate, and in plain Dart projects you can call Isolate.run directly.
On the server, when there are many cores, each isolate can listen on the same port with HttpServer.bind(..., shared: true) so requests are spread across all cores. But measure the work first: for a task that takes only a few milliseconds, the cost of starting an isolate and copying data can outweigh the benefit.
Common mistakes
Common mistakes
Using an isolate to wait
Waiting for an HTTP response, a Future.delayed or a file read does not use the CPU; it waits for the operating system. await already handles that without blocking. Wrapping it in Isolate.run only adds startup and copying cost.
Expecting shared variables
Doing counter += 100 inside Isolate.run and reading counter in main gives 0, not 100, because every isolate has its own copy of each top-level variable. Return the result from the closure and apply it on the caller's side.
Capturing something huge or unsendable
A closure copies every object it captures. A closure written inside a method that captures this copies the whole instance, including any large lists inside it. Capturing a ReceivePort fails with an ArgumentError. Pull out just the values you need into local variables and capture those.
Leaving a ReceivePort open
If you open a ReceivePort with port.listen(print) and never close it, the process keeps running after main() returns, because an open port keeps the isolate alive. Send the worker a 'stop' message and close the port on both sides.
Best practices
Best practices
- Measure with a Stopwatch before reaching for an isolate; if the work takes a few milliseconds, keep it on the main isolate.
- Use Isolate.run for a single job and Isolate.spawn only for a worker that receives many messages.
- Keep messages small: send ids or results rather than whole object graphs.
- Give every worker a 'stop' message and close the ports on both sides.
Mini challenge
Split the search across isolates
Take the Collatz sequence: divide n by 2 when it is even, otherwise compute 3n+1, and count the steps until n reaches 1. Find the start value from 1 to 100000 with the most steps. Compute it once serially, then once split across four isolates, and check that the answers agree.
- collatzSteps(start) returns the number of steps to reach 1
- longestInRange(from, to) returns a (start, steps) record for the most steps in [from, to)
- longestParallel(limit, parts) splits 1..limit into parts chunks, runs each with Isolate.run and combines them with Future.wait
- main() prints the serial and parallel answers and whether they are equal
import 'dart:isolate';
int collatzSteps(int start) {
// TODO: halve when even, 3n + 1 when odd, until n == 1; count the steps
}
(int, int) longestInRange(int from, int to) {
// TODO: return (startWithMostSteps, itsSteps) for starts in [from, to)
}
Future<(int, int)> longestParallel(int limit, int parts) async {
// TODO: split 1..limit into equal chunks
// TODO: run longestInRange for each chunk with Isolate.run
// TODO: wait for all of them and return the entry with the most steps
}
Future<void> main() async {
// TODO: print the serial answer for 1..100000 and the parallel one (4 parts)
// TODO: print whether the two answers are equal
// TODO: print the parallel answer for limit 10 split in 2 parts
}Expected: Four lines: serial: start 77031, 350 steps, parallel: start 77031, 350 steps, same answer: true and small check: (9, 19).
Show hint
Compute the chunk size with (limit / parts).ceil(). Inside the loop, capture from and to as final variables in the Isolate.run closure. Compare with > rather than >= so ties keep the earlier start.
Show solution
import 'dart:isolate';
int collatzSteps(int start) {
var n = start;
var steps = 0;
while (n != 1) {
n = n.isEven ? n ~/ 2 : 3 * n + 1;
steps++;
}
return steps;
}
(int, int) longestInRange(int from, int to) {
var bestStart = from;
var bestSteps = -1;
for (var n = from; n < to; n++) {
final steps = collatzSteps(n);
if (steps > bestSteps) {
bestStart = n;
bestSteps = steps;
}
}
return (bestStart, bestSteps);
}
Future<(int, int)> longestParallel(int limit, int parts) async {
final size = (limit / parts).ceil();
final jobs = <Future<(int, int)>>[];
for (var i = 0; i < parts; i++) {
final from = 1 + i * size;
final to = from + size > limit + 1 ? limit + 1 : from + size;
jobs.add(Isolate.run(() => longestInRange(from, to)));
}
final results = await Future.wait(jobs);
var best = results.first;
for (final r in results) {
if (r.$2 > best.$2) best = r;
}
return best;
}
Future<void> main() async {
final serial = longestInRange(1, 100001);
final parallel = await longestParallel(100000, 4);
print('serial: start ${serial.$1}, ${serial.$2} steps');
print('parallel: start ${parallel.$1}, ${parallel.$2} steps');
print('same answer: ${serial == parallel}');
print('small check: ${await longestParallel(10, 2)}');
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A busy loop blocks the event loop, and async/await does not move computation elsewhere
- Each isolate has its own memory and event loop and talks only by messages, which are copied
- Use Isolate.run for one job and Isolate.spawn with ReceivePort and SendPort for a long-lived worker
- Do not use isolates for waiting on I/O, only for CPU-bound work, and remember to close ports
Concurrency in Dart — Dart