Isolates
suggest changeUnlike languages that employ shared-memory multithreading with locks and mutexes, Dart achieves concurrency through an actor-based model called Isolates.
Every Dart program runs inside an initial isolate (the main thread). Each isolate contains:
- Its own dedicated thread of execution.
- An independent event loop.
- A private memory heap that is never shared with any other isolate.
Because memory is strictly isolated, Dart applications are inherently immune to data races, deadlocks, and thread synchronization issues.
When to Use Isolates
- Use standard
async/awaitfor I/O: Network requests, file reading, and database queries are non-blocking and handled asynchronously on the main event loop without needing extra isolates. - Use Isolates for CPU-intensive computation: Heavy JSON parsing (megabytes of data), image/audio transformations, cryptography, and complex mathematical calculations that would otherwise freeze the UI or event loop.
Simple Background Computation: Isolate.run()
For one-off computational tasks, Dart provides Isolate.run(). It spawns a background isolate, executes the given callback, passes the result back, and terminates the isolate cleanly:
import 'dart:isolate';
// CPU-intensive task (e.g. calculating nth Fibonacci number)
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
void main() async {
print('Starting heavy computation on background isolate...');
// Runs on a separate worker thread without blocking the main event loop
final result = await Isolate.run(() => fibonacci(42));
print('Fibonacci(42) = $result');
}
Isolate.run() automatically manages port creation, exception forwarding, and worker lifecycle.
Long-Lived Isolates with Two-Way Message Passing
When performing continuous background processing (such as a worker pool or audio decoder), spawning and killing isolates repeatedly is inefficient. Instead, keep a worker isolate running and communicate via ReceivePort and SendPort.
import 'dart:async';
import 'dart:isolate';
// Messages sent to the worker
class WorkerTask {
final int id;
final String payload;
WorkerTask(this.id, this.payload);
}
// Background entry point must be a top-level or static function
void _workerEntryPoint(SendPort sendPort) {
// 1. Create a receive port for the worker to receive tasks
final receivePort = ReceivePort();
// 2. Send the worker's SendPort back to the main isolate
sendPort.send(receivePort.sendPort);
// 3. Listen for incoming work
receivePort.listen((message) {
if (message is WorkerTask) {
// Process task
final processed = 'Processed task #${message.id}: ${message.payload.toUpperCase()}';
// Reply to main isolate
sendPort.send(processed);
} else if (message == 'SHUTDOWN') {
receivePort.close();
Isolate.current.kill();
}
});
}
void main() async {
final mainReceivePort = ReceivePort();
// Spawn the background isolate
final isolate = await Isolate.spawn(_workerEntryPoint, mainReceivePort.sendPort);
// Convert the receive port stream into a broadcast stream or stream iterator
final stream = mainReceivePort.asBroadcastStream();
// Await the worker's SendPort (the first message sent from worker)
final workerSendPort = await stream.first as SendPort;
// Listen for worker replies
final sub = stream.listen((message) {
print('Main received: $message');
});
// Dispatch work to the worker isolate
workerSendPort.send(WorkerTask(1, "invoice parsing"));
workerSendPort.send(WorkerTask(2, "image thumbnailing"));
// Give tasks time to execute, then cleanly shut down
await Future.delayed(const Duration(milliseconds: 500));
workerSendPort.send('SHUTDOWN');
await sub.cancel();
mainReceivePort.close();
print('Worker isolate shut down.');
}
Fast Binary Data Transfer with TransferableTypedData
Normally, messages sent across SendPort are copied into the recipient's heap. For massive binary payloads (like camera frames or audio buffers), copying incurs memory overhead.
TransferableTypedData transfers byte buffers with zero-copy (move) semantics. fromList copies the data once into the transferable buffer; sending it to another isolate and calling materialize() there then moves that buffer without copying again:
import 'dart:isolate';
import 'dart:typed_data';
void processBuffer(TransferableTypedData transferable) {
// Materialize bytes on the receiving isolate
final byteBuffer = transferable.materialize().asUint8List();
print('Received buffer with ${byteBuffer.length} bytes.');
}
void main() {
final rawData = Uint8List(1024 * 1024 * 10); // 10 MB buffer
// Create transferable container (copies rawData; rawData stays usable)
final transferable = TransferableTypedData.fromList([rawData]);
Isolate.run(() => processBuffer(transferable));
}
Best Practices
- Prefer
Isolate.run()for one-shot tasks: Avoid boilerplateReceivePort/SendPortcode unless long-lived stateful worker communication is required. - Top-level or static worker functions: The entry point passed to
Isolate.spawn()must be a top-level function or static class method. - Do not share mutable references: Only send sendable primitive types, maps, lists, or
TransferableTypedDataacross ports. - Always terminate long-lived isolates: Close ports and invoke
isolate.kill()when background processing is complete to release system threads and memory.