Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 61 ยท Asynchronous Dart

Isolates and Concurrency

Learn how Dart runs work in parallel with isolates: Isolate.run, ports, message passing and why nothing is shared, with runnable stand-ins.

A Dart program normally runs on one thread. Futures and streams let that thread juggle many waiting tasks (network, files, timers), but they do not make heavy calculations faster: if you decode a 50 MB JSON file or compress an image on the main thread, nothing else runs until you finish. In a Flutter app that means a frozen screen.

To use more than one CPU core, Dart gives you isolates. An isolate is an independent worker with its own memory and its own event loop. Isolates cannot touch each other's objects. They only talk by sending messages. This design removes a whole family of bugs (data races, locks, deadlocks on shared state) at the price of copying data between workers.

The Dart snippets are read-only because the site has no Dart runtime. The TypeScript stand-ins use Node worker threads and structuredClone, which follow the same model: separate memory and message passing.

What an isolate is

Think of each isolate as a tiny program inside your program. It has:

  • its own heap, so objects created in one isolate are invisible to the others;
  • its own event loop and microtask queue;
  • its own copy of every static and top-level variable;
  • a port through which it receives messages.

Because nothing is shared, there is no need for locks. The garbage collector can also work per isolate without stopping the whole program.

flowchart LR
    subgraph Main["Main isolate"]
      M1["Own heap"]
      M2["Own event loop"]
    end
    subgraph Worker["Worker isolate"]
      W1["Own heap"]
      W2["Own event loop"]
    end
    Main -- "message (copied)" --> Worker
    Worker -- "result (copied)" --> Main

Two isolates never share objects. Data travels through messages.

The easy way: Isolate.run

Since Dart 2.19 the simplest tool is Isolate.run. You pass it a function, Dart starts a short-lived isolate, runs the function there, sends the result back and shuts the isolate down. You just await the result:

DART
import 'dart:isolate';

int sumOfSquares(int n) {
  var total = 0;
  for (var i = 1; i <= n; i++) {
    total += i * i;
  }
  return total;
}

Future<void> main() async {
  print('Starting');
  final result = await Isolate.run(() => sumOfSquares(100000000));
  print('Result: $result');
}

While the worker computes, the main isolate stays free. In a Flutter app the UI keeps animating. Isolate.run returns a Future<R>, so everything you know about await, try/catch and Future.wait applies.

If the function throws, the error is sent back and rethrown in the caller:

DART
try {
  await Isolate.run(() => int.parse('not a number'));
} on FormatException catch (e) {
  print('The worker failed: ${e.message}');
}
TypeScript Offloading work to a worker (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

What can be sent in a message

Messages are copied into the receiving isolate's heap. Most everyday values are fine:

  • null, bool, int, double, String;
  • lists, maps and sets of sendable values;
  • plain objects whose fields are sendable;
  • SendPort, Capability, typed data such as Uint8List;
  • closures, as long as everything they capture can be sent.

Things bound to the running system cannot cross: a ReceivePort, a Socket, a File handle, a Stream or objects that hold native resources. The most common surprise is a closure that captures this of a big object holding such a field: the whole object has to be copied, and sending fails at run time.

Because copying costs time, sending a huge list back and forth can cancel the benefit of the worker. Two tricks help. First, send small inputs (a file path, not the file contents) and let the worker load the data itself. Second, return the result with Isolate.exit, which transfers the result instead of copying it. Isolate.run already does this for its return value.

TypeScript Messages are copies (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Ports: talking to a long-lived isolate

Isolate.run is perfect for one job. When a worker should stay alive and handle many requests (for example a parser that keeps a cache), you use ports. A ReceivePort is the listening end and is a stream of messages. A SendPort is the sending end; it can be handed to another isolate.

DART
import 'dart:isolate';

// Runs inside the worker isolate.
void worker(SendPort toMain) {
  final fromMain = ReceivePort();
  toMain.send(fromMain.sendPort); // tell main how to reach us

  fromMain.listen((message) {
    if (message == 'stop') {
      fromMain.close();
      return;
    }
    final (id, number) = message as (int, int);
    toMain.send((id, number * number));
  });
}

Future<void> main() async {
  final fromWorker = ReceivePort();
  await Isolate.spawn(worker, fromWorker.sendPort);

  late SendPort toWorker;
  var replies = 0;

  await for (final message in fromWorker) {
    if (message is SendPort) {
      toWorker = message;
      toWorker.send((1, 7));
      toWorker.send((2, 9));
    } else {
      final (id, square) = message as (int, int);
      print('Reply $id: $square');
      if (++replies == 2) {
        toWorker.send('stop');
        fromWorker.close();
      }
    }
  }
}

The handshake is the part to understand. Isolate.spawn can only pass one initial message, so the main isolate hands the worker a SendPort of its own. The worker answers by sending back its SendPort. From then on both sides can talk. Records make good messages because you can send (id, payload) and match them with a pattern on arrival. An id lets you match replies to requests when answers can come back in any order.

Always close ports you no longer need. An open ReceivePort keeps its isolate alive, so a forgotten one stops a command-line program from ever exiting.

TypeScript A request and reply protocol (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Choosing a tool

Situation Use
Waiting for network, disk or a timer Future / Stream, no isolate needed
One heavy calculation (decode, compress, sort) Isolate.run
A worker that must stay alive and answer many requests Isolate.spawn with ports
Splitting a big job over all cores Several Isolate.run calls with Future.wait

Isolates are not free: starting one costs a few milliseconds and some memory. A calculation shorter than a frame or two is cheaper to do in place. Measure before you move work, as described in performance and memory.

Two more facts are worth knowing. Dart compiled to JavaScript has no isolates, so on the web you use web workers instead. And Flutter's compute() function is only a thin wrapper around Isolate.run; new code can call Isolate.run directly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main reason Dart isolates need no locks?

    Each isolate has its own heap. Since no object is shared, there is nothing to protect with a lock.
  2. 2. What does await Isolate.run(() => work()) return?

    Isolate.run starts a short-lived isolate, runs the function, returns its result as a Future and shuts the worker down.
  3. 3. Which value usually cannot be sent in a message?

    Values tied to native resources such as ports, sockets and file handles cannot be copied to another isolate.
  4. 4. Why should a long-lived worker be given a way to stop and its ports be closed?

    A ReceivePort that is still open can receive messages, so its isolate does not exit. A forgotten port keeps the program running.

Summary

  • An isolate has its own heap and event loop; isolates share nothing and communicate by messages.
  • Isolate.run(() => ...) runs one job in a worker and returns a Future; errors are rethrown in the caller.
  • Messages are copied (sendable values only); Isolate.exit transfers a result without copying.
  • Use Isolate.spawn with a ReceivePort/SendPort handshake for long-lived workers, and close ports when done.
  • Futures handle waiting; isolates handle heavy computation. Measure before moving work to a worker.

Next: JSON and serialization.