Sub topic 2
Isolates: separate heaps, message passing
This chapter assumes you know basic Dart, including async/await and Future. It also assumes you know why long synchronous work blocks the event loop and drops frames in a Flutter app. Here you will learn what an isolate is and what it does not share with other isolates. You will also learn how isolates communicate, which is the basis for every later chapter.
The problem isolates solve
In most languages, you run work in parallel with threads that share memory. Shared memory is fast, but it leads to data races, deadlocks, and locks scattered through your code.
Dart chose a different model. The unit of concurrency is the isolate. An isolate is an independent worker with its own memory and its own event loop. Code in one isolate cannot reach into another isolate's objects. The only way for isolates to cooperate is to send each other messages.
Every Dart program starts with one isolate, the main isolate. In Flutter, this is the isolate that runs your main() function, builds widgets, and handles user input. If it is busy, frames are late.
What an isolate owns
Each isolate has its own:
- Heap. Every object you create lives in the heap of the isolate that created it. No other isolate can hold a reference to it.
- Event queue and microtask queue. The isolate runs one event at a time, to completion, as you saw in the event-loop chapter. Two isolates have two separate loops, so a busy one does not delay the other.
- Static and top-level variables. Each isolate gets its own copy. This surprises many developers, and the example below shows it.
- Single thread of execution. Within an isolate, only one piece of Dart code runs at a time. You never need a lock to protect a field inside one isolate.
Isolates are not the same as operating system threads. The Dart VM runs isolates on a pool of OS threads and decides which thread runs which isolate. You do not choose or see the thread. You can have more isolates than CPU cores, but only as many run at the same moment as there are cores for them.
Isolates compared with threads
| Aspect | Threads (typical shared-memory model) | Dart isolates |
|---|---|---|
| Memory | Shared between threads | Separate heap per isolate |
| Communication | Reading and writing shared objects | Sending messages through ports |
| Synchronization | Locks, mutexes, atomics | None needed for isolate-local state |
| Data races | Possible | Not possible on isolate-local objects |
| Cost to start | Low | Higher, because the isolate needs its own heap and event loop |
| Passing data | Pass a reference | Usually copy the data |
The last two rows are the trade-off. You gain safety and give up cheap sharing.
Seeing the separation
The following program changes a list and a global variable inside a worker isolate. Then it checks what the main isolate sees. It needs Dart 3 because it uses a record.
import 'dart:isolate';
int counter = 0; // top-level variable: every isolate has its own copy
Future<void> main() async {
final names = ['ada', 'grace'];
counter = 1;
final seenByWorker = await Isolate.run(() {
names.add('linus'); // changes the worker's copy of the list
counter += 10; // the worker's counter starts at 0, not 1
return (names.length, counter);
});
print('worker saw: $seenByWorker'); // (3, 10)
print('main names: $names'); // [ada, grace]
print('main counter: $counter'); // 1
}Three things happen here:
- The closure passed to
Isolate.runrefers tonames. Because the worker cannot share the main isolate's list, the VM copies the list into the worker's heap along with the closure. - The worker adds an element to its copy. The main isolate's list is unchanged.
- The worker's
counteris a fresh variable, initialized from its initializer (0). The assignmentcounter = 1inmainnever reaches it.
How messages move between isolates
Isolates talk through two kinds of port objects from dart:isolate:
- A
ReceivePortis the receiving end. It is aStreamof incoming messages that you can listen to. - A
SendPortis the sending end. It is tied to oneReceivePort, and callingsenddelivers a message to that port. ASendPortcan itself be sent in a message, which is how two isolates set up a conversation.
Here is the smallest useful example. The worker receives a SendPort as its start-up argument and uses it to reply.
import 'dart:isolate';
void hello(SendPort reply) {
reply.send('hi from ${Isolate.current.debugName}');
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(hello, port.sendPort, debugName: 'helper');
// `first` listens for one message, then cancels the subscription,
// which also closes the port so the program can exit.
print(await port.first); // hi from helper
}Isolate.spawn starts a new isolate that runs hello with the given argument. The debugName is a label that shows up in debugging tools and in Isolate.current.debugName. A later chapter covers spawn and ports in detail, including long-lived workers. For now, notice the shape of the exchange: data goes in as a message and a result comes back as another message. Nothing is shared.
A program stays alive while any isolate has an open ReceivePort or pending work. If you forget to close a port that you no longer need, the program may never exit. This is a common reason a command-line Dart program hangs after it looks finished.
Messages are copied
When you send a message, the VM generally makes a copy of the object graph in the receiving isolate's heap. The receiver gets an object that looks the same, but it is a different object. Changing it does not affect the original, and the reverse is also true.
This copy has two consequences you should plan for:
- Cost grows with size. Sending a small record or a short string is cheap. Sending a list of a million objects means walking and duplicating all of them, and that work happens on one of the isolates involved. A large copy on the main isolate can itself cause jank.
- Identity is lost. The copy is not
identicalto the original. Two references to the same object inside one message stay a single shared object in the copy, because the VM copies the whole graph in one pass. But a reference you send in two separate messages arrives as two separate objects.
There are exceptions that reduce copying. The VM may share some deeply immutable values rather than duplicate them. Isolate.exit can hand the final message to the receiver without copying, and Isolate.run uses it to return its result. TransferableTypedData moves large byte buffers. Treat these as optimizations, not as guarantees you rely on for correctness. The next chapters on sendable values and large data cover them.
Isolate groups and what they share
Isolates started with Isolate.spawn or Isolate.run from an existing isolate join the same isolate group. The group shares the compiled program code, so a new isolate does not need to load or compile your app again. This makes starting an isolate much cheaper than it was before Dart 2.15, and it explains why spawning is fast enough for on-demand work.
Sharing code does not break the isolation rule. The group shares the instructions, not the data. Every isolate still has its own heap and its own copies of statics.
What isolation does not protect you from
Isolation removes data races on objects, but it does not remove all concurrency problems:
- Ordering. Messages from one isolate arrive in the order they were sent. Messages from different isolates have no guaranteed order relative to each other. Your logic must not depend on one.
- Outside resources. Two isolates can write to the same file, database, or socket. The operating system and the resource decide what happens, and Dart cannot protect you.
- Request and response pairing. If you send several requests to one worker, nothing connects a reply to its request unless you add an identifier. The long-lived worker chapter does this with a record containing an
id. - Overhead. Spawning an isolate, copying data, and waiting for a reply all take time. A small job can finish faster on the main isolate than it would after the round trip. The chapter on when an isolate is worth it covers how to decide.
Common mistakes
- Expecting shared state. Mutating an object in a worker and expecting the main isolate to see it. The change happens on a copy.
- Assuming a global is set. Reading a top-level variable in a worker and getting its initial value instead of the value the main isolate assigned.
- Treating an isolate as a free thread. Starting one isolate per small task adds start-up and copy costs that can exceed the work saved.
- Leaving ports open. Keeping a
ReceivePortopen after the last message, so the program or the worker never terminates.
Key points
- An isolate is an independent worker with its own heap, event queue, microtask queue, and static variables.
- Isolates share no mutable state. They communicate by sending messages through
SendPortand receiving them onReceivePort. - Messages are normally copied, so the cost of a message grows with its size, and changes on one side never reach the other.
- Isolates in one group share compiled code but not data, which keeps spawning relatively cheap.
- Isolation prevents data races on objects. It does not order messages across isolates or protect external resources.
Exercise
A Flutter app keeps a static final Map<String, String> cache on a class and fills it in main(). A worker isolate started with Isolate.run reads cache['token'] and gets null, although the main isolate has the value. Explain why, and name two ways to fix it.
Show answer
Static fields are per isolate. The worker has its own cache, which starts empty and is never filled by the main isolate's code. To fix it, either read the needed value in the main isolate and pass it into the worker (for example by capturing a local variable final token = cache['token']; in the closure, or by passing it as an argument), or have the worker initialize its own state, for example by loading the value itself. Do not expect changes to propagate back and forth automatically.
Exercise
In the program from "Seeing the separation", what would main names print if the Isolate.run closure returned the names list after adding 'linus', and the main isolate then printed seenByWorker and names? Explain what you would see for each.
Show answer
seenByWorker would be the list [ada, grace, linus], because the worker's modified copy is sent back as the result. names in the main isolate would still print [ada, grace], because it is the original list, which the worker never touched. The returned list is a different object from the original, so the two lists are independent.