DART / CHAPTER 13

Isolates and message-owned work

Advanced

Move expensive work without assuming shared mutable state.

By the end of this chapter

  • Distinguish async waiting from CPU parallelism
  • Explain isolate memory separation
  • Choose sendable messages and explicit results

The idea

Async and await let an isolate continue other event-loop work while an operation waits; they do not automatically move a CPU-heavy loop to another isolate. A long synchronous computation can still delay responsiveness. Isolates provide separate execution contexts with their own mutable state, communicating through messages instead of sharing ordinary mutable objects.

For suitable native Dart environments, Isolate.run can execute a computation elsewhere and return its result through a Future. Inputs and results must satisfy the relevant message-transfer rules. Keep transferred data focused and avoid accidentally capturing a large object graph in a closure. Measure communication overhead as well as compute time, because moving a tiny operation can cost more than performing it locally.

Dart example
import "dart:isolate";
Future<void> main() async {
  final total=await Isolate.run(() => [2,3,5].fold<int>(0,(a,b)=>a+b));
  print(total);
}
Result
10

The example requires an environment supporting dart:isolate; it is not a promise of execution in every browser editor.

Try it yourself

Design a message containing only the data needed to compute a large report, and return a compact summary.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Why can an async function containing a long synchronous loop still freeze an interface?