Sub topic 5
What you can send, and what gets copied
This chapter assumes you can write async/await code, you know what Isolate.run does, and you know that isolates have separate heaps. Here you will learn which values can cross an isolate boundary, what a copy means for your code, and which mistakes cause errors or surprising behavior.
The rule: messages are copies
Isolates share no mutable memory. Anything that moves from one isolate to another is a message. For ordinary objects, the receiving isolate gets a copy of the object graph, not a reference into the sender's heap.
You send data in these situations:
- You call
SendPort.send(message). - You pass an argument to
Isolate.spawn. Isolate.runcopies the closure, and everything it captures, to the new isolate.Isolate.runreturns its result to the caller. This direction usually does not copy (see "Results coming back" below).
The next example shows the consequence. The worker changes its copy, and the original stays the same.
import 'dart:isolate';
Future<void> main() async {
final original = <String, List<int>>{
'a': [1, 2, 3],
};
final lengthInWorker = await Isolate.run(() {
// `original` was copied into the worker. This changes only the copy.
original['a']!.add(4);
return original['a']!.length;
});
print(lengthInWorker); // 4
print(original['a']); // [1, 2, 3]
}If you expect a worker to update an object in place, it will not. The worker has to return the new value, or send it back in a message, and the caller has to use that value.
What can be sent
Dart 2.15 and later can send most objects, not only a fixed list of core types. The table groups what you will meet in practice.
| Kind of value | Sendable? | Notes |
|---|---|---|
| `null`, `bool`, `int`, `double`, `String` | Yes | Primitives. |
| `List`, `Map`, `Set` | Yes | Contents must be sendable too. The collection is copied deeply. |
| Records | Yes | Fields must be sendable. |
| `Uint8List` and other typed data | Yes | Copied by default. See `TransferableTypedData` for the no-copy path. |
| `SendPort` | Yes | This is how isolates exchange communication channels. |
| `Capability` | Yes | An opaque token, used by `Isolate.pause` and `Isolate.resume`. |
| `TransferableTypedData` | Yes | Moves bytes without the usual copy. |
| Instances of your own classes | Yes | Fields must be sendable. The receiver gets an instance of the same class. |
| Closures and function references | Yes, with caveats | Top-level and static functions are simple. A closure copies its captured context. |
| `ReceivePort` | No | Only its `SendPort` can be sent. |
| Objects wrapping native resources | No | Examples are `Socket`, `RandomAccessFile`, `Pointer` from `dart:ffi`, and `DynamicLibrary`. |
| Objects whose class implements `Finalizable` | No | Their lifetime is tied to a single isolate. |
| `UserTag` and mirror objects | No | Tied to the sending isolate. |
An unsendable value anywhere in the graph makes the whole send fail. A List of 10,000 strings with one Socket hidden inside it is not sendable.
Your own classes
You do not need to mark a class in any way. A plain data class works:
import 'dart:isolate';
class Point {
Point(this.x, this.y);
final double x;
final double y;
double distanceTo(Point other) {
final dx = x - other.x;
final dy = y - other.y;
return (dx * dx + dy * dy);
}
}
Future<void> main() async {
final points = [Point(0, 0), Point(3, 4), Point(6, 8)];
final result = await Isolate.run(() {
var total = 0.0;
for (var i = 1; i < points.length; i++) {
total += points[i].distanceTo(points[i - 1]);
}
return total;
});
print(result); // 50.0
}The Point objects exist twice, once in each heap. The method code is not copied, because every isolate in the same program already has the same class definitions. Only the field values move.
Unsendable values fail loudly
Sending a ReceivePort is an error. The error text includes "Illegal argument in isolate message", followed by a description of the offending object.
import 'dart:isolate';
Future<void> main() async {
final port = ReceivePort();
try {
// The closure captures `port`, and a ReceivePort cannot be copied.
await Isolate.run(() => port.hashCode);
} catch (e) {
print('Send failed: $e');
} finally {
port.close();
}
}The failure happens when the closure is copied, before any of your worker code runs. The cause is therefore always something the calling side handed over, not something in the worker's logic.
Identity and cycles inside one message
A single message is copied as a graph, and the copy keeps the graph's shape. If two fields in your message point to the same object, they point to one shared object in the copy too. Cyclic references also survive.
import 'dart:isolate';
Future<void> main() async {
final shared = <int>[1, 2, 3];
final pair = [shared, shared];
final stillShared = await Isolate.run(() {
return identical(pair[0], pair[1]);
});
print(stillShared); // true
}This sharing only holds inside one message. Two separate send calls with the same list produce two unrelated copies on the other side. Do not use identical across messages to detect "same object as before". Use an explicit id.
Cost of copying
A copy costs time in proportion to the size of the graph, and it happens on the sending isolate. That has three practical consequences:
- Sending a large structure from the UI isolate blocks the UI isolate while the copy is made. A worker that saves you 50 ms of computation but costs 40 ms of copying is barely worth the trouble.
- Memory use can briefly double, since both copies exist until one is garbage collected.
- A graph with many small objects costs more than one flat buffer of the same size. A
List<Map<String, dynamic>>with 100,000 entries is far slower to send than a singleUint8Listholding the same data.
When messages are large, you have three choices: send a more compact form, use TransferableTypedData to avoid the copy (a later chapter covers it), or have the worker do both the loading and the processing so the big data never crosses the boundary.
Results coming back
Isolate.run returns its result with a different mechanism from ordinary sends. When the computation finishes, the worker isolate exits and hands its result to the caller without copying it. The check that the object is sendable is still done, but the transfer is close to constant time, even for a big list. This makes Isolate.run a good fit for "read a large file, parse it, return the parsed tree". Only the input needs to be small.
You should not depend on exact performance details of the runtime. Measure with your real data when it matters.
Closures, globals, and what is not shared
Two kinds of state surprise people at the boundary.
Captured variables. A closure sent to a new isolate brings a copy of everything it captures. In a method, referring to a field captures this, and so the whole object. The chapter on closure capture covers this pitfall in detail. For now, remember that a closure is a message like any other, and its contents have to be sendable.
Top-level and static variables. Each isolate has its own copy of every top-level and static variable, initialized from scratch when the isolate first uses it. Changing a global in the main isolate does not change it in the worker.
import 'dart:isolate';
int counter = 0;
Future<void> main() async {
counter = 5;
final inWorker = await Isolate.run(() {
// This is the worker's own `counter`, initialized to 0.
return counter;
});
print(inWorker); // 0
print(counter); // 5
}This catches people who keep configuration, caches, or singletons in globals. Such state has to be passed in as a message, or built again inside the worker.
Common mistakes
- Expecting in-place updates. Mutating a received list changes only the worker's copy. Return the result.
- Sending a whole model object when the worker needs one field. The copy cost grows with the graph. Extract the field into a local variable first.
- Putting a handle in a message. A database connection, a socket, or a file handle is a native resource and fails. Pass the path or the connection settings instead, and open the resource inside the worker.
- Relying on identity across messages. Each
sendcopies on its own. - Sending a
ReceivePort. Send itssendPortinstead.
Exercise
A worker receives {'items': shared, 'backup': shared} where shared is one List<int> in the sender. The worker calls msg['items'].add(9). What does msg['backup'] contain in the worker, and what does shared contain in the sender?
Show answer
In the worker, msg['backup'] also contains the 9, because both entries point to one list inside a single message and the copy keeps that sharing. In the sender, shared is unchanged, because the worker modified its own copy. If the sender needs the new list, the worker must send it back or return it.
Exercise
You want a worker to parse a file that is open in the main isolate as a RandomAccessFile. Why does passing the RandomAccessFile to Isolate.run fail, and what should you pass instead?
Show answer
A RandomAccessFile wraps a native resource that belongs to one isolate, so it is unsendable and the send raises an "Illegal argument in isolate message" error. Pass the file path (a String), and open and read the file inside the worker.