Isolate vs thread
- Dart course
- Advanced
- Lesson 5/83
- 5 min
Learn the difference between isolates and threads.
Isolate vs thread
In classic languages threads share memory; this requires lock, mutex, condition variable and similar tools. Mistakes easily become race conditions.
In Dart, isolates do not share memory. Each isolate owns its stack and objects. Data is copied as a message.
Result: Dart needs no locks, but pays a copy cost. Spawning an isolate is expensive for small work; use it only for genuinely heavy work.
When to use an isolate?
Good use: CPU-heavy work taking more than 50 ms — JSON parsing, image processing, file scanning. Keeping these on the main isolate freezes the UI.
Bad use: 5 ms computations. The isolate spawn cost (copy + scheduling) exceeds the work itself. Plain synchronous code is enough.
I/O waiting (network, disk) needs no isolate; Future and async/await suffice. Isolates are for CPU work.
Practice Run heavy work with Isolate.run
Define int kareToplam(int n) that returns the sum of squares from 1 to n. Make main async; add var result = await Isolate.run(() => kareToplam(100)); and print(result);.
Starter code
import 'dart:isolate';
void main() {
// define kareToplam function (outside main)
// make async; add Isolate.run call with kareToplam(100)
}Sample solution
import 'dart:isolate';
int kareToplam(int n) {
var t = 0;
for (var i = 1; i <= n; i++) {
t += i * i;
}
return t;
}
void main() async {
var result = await Isolate.run(() => kareToplam(100));
print(result);
}Expected output
338350
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool is not needed?
Isolates do not need ____.
Isolates do not need lock.
Explanation: isolates do not share memory, so no lock is needed.
2 Comparison table
| Term | Meaning |
|---|---|
Thread |
Shares memory |
Isolate |
Does not share memory |
Lock |
Needed in threads |
Message |
Transfer in isolates |
3 When is spawning an isolate pointless?
- A 5 ms addition Correct answer
- Resizing a 4K image
- Parsing 10 MB of JSON
- Reading a 10k-row CSV
Explanation: for 5 ms work the spawn cost exceeds the work itself.