Dart Concurrency and Isolates
Concurrency is the ability to handle multiple tasks at the same time.
Dart's concurrency model differs from traditional multithreading; it uses Isolate (isolation) to achieve parallel computing.
This chapter introduces Dart's concurrency model, the concept and use of Isolate, and the message-passing mechanism.
Dart Concurrency Model
Most programming languages use a shared-memory multithreading model, where multiple threads share the same memory space.
The downside of this model is that it easily leads to race conditions and deadlocks.
Dart takes a different approach: each Isolate has its own independent memory heap, and Isolates do not share memory.
They communicate through message passing, which fundamentally avoids data race problems.
Dart's concurrency model has three levels:
| Level | Mechanism | Applicable scenarios |
|---|---|---|
| Event loop | Single-threaded asynchronous (Event Loop) | I/O operations, timers, user interaction |
| Isolate | Independent memory + message passing | CPU-intensive computation |
| Future/Stream | Asynchronous programming syntax | Most everyday development scenarios |
The concurrency needs of most Dart programs can be met with async/await and Future/Stream. Isolate is only necessary when you need to perform large amounts of CPU-intensive computation. Introducing Isolate too early complicates the code with little benefit.
Isolate Concepts and Usage
An Isolate is Dart's unit of concurrency; each Isolate has its own independent memory and event loop.
The main program itself runs in one Isolate (the main Isolate).
Create a New Isolate with Isolate.spawn
Example
import
'dart:isolate'
;
// This function runs in the new Isolate
// SendPort is used to send messages to the main Isolate
void
heavyComputation
(
SendPort sendPort
)
{
(
'New Isolate starts computing...'
)
;
// Simulate a CPU-intensive computation
int
sum
=
0
;
for
(
int
i
=
1
;
i
<=
10000000
;
i
++
)
{
sum
=
i
;
}
// Send the computation result back to the main Isolate
sendPort.
send
(
sum
)
;
(
'New Isolate finished computing, result sent'
)
;
}
Future
<
void
main
(
)
async
{
print
('Main Isolate started'
)
;
// Create a ReceivePort to receive messages
var
receivePort
=
ReceivePort
(
)
;
// spawn creates a new Isolate
await Isolate.
spawn
(
heavyComputation
,
receivePort.
sendPort
)
;
(
'The main Isolate can do other things while waiting for the result...'
)
;
// Wait for the computation result from the new Isolate
var
result
=
await receivePort.
first
;
(
'RUNOOB computation result: sum from 1 to 10000000 = $result'
)
;
receivePort.
close
(
)
;
(
'Main Isolate finished'
)
;
}
主 Isolate 启动
主 Isolate 在等待结果的同时可以做其他事情...
新 Isolate 开始计算...
新 Isolate 计算完成,结果已发送
RUNOOB 计算结果: 1 到 10000000 的和 = 50000005000000
主 Isolate 结束
Comparison: Performance Difference With and Without Isolate
Example
// Execute a CPU-intensive task in the main Isolate (it will block)
int
fibonacci
(
int
n
)
{
if
(
n
<=
1
)
return
n
;
return
fibonacci
(
n
1
)
fibonacci
(
n
2
)
;
}
void
main
(
)
{
// Compute in the main Isolate -- it will block all other operations
var
startTime
=
DateTime.
now
(
)
;
// Note: if n is too large, this computation will be very time-consuming
// In real development, this kind of computation should be put in a separate Isolate
var
result
=
fibonacci
(
40
)
;
var
elapsed
=
DateTime.
now
(
)
.
difference
(
startTime
)
;
(
'RUNOOB Fibonacci(40) = $result'
)
;
(
'Elapsed: ${elapsed.inMilliseconds}ms'
)
;
(
'(Note: during computation, the main Isolate cannot handle other tasks)'
)
;
}
In a Flutter app, performing a time-consuming synchronous computation in the main Isolate will cause the UI to freeze. The solution is to move the computation into a separate Isolate, then send the result back via a message and update the UI once it completes.
Message-Passing Mechanism
Isolates pass messages between each other through SendPort and ReceivePort.
Messages must be serializable (primitive types, String, List, Map, etc.); functions or closures cannot be passed.
Two-Way Communication
Example
import
'dart:isolate'
;
// The worker function running in the new Isolate
void
workerIsolate
(
SendPort mainSendPort
)
{
// Create its own ReceivePort to receive messages from the main Isolate
var
workerReceivePort
=
ReceivePort
(
)
;
// First send the worker's SendPort to the main Isolate to establish a two-way channel
mainSendPort.
send
(
workerReceivePort.
sendPort
)
;
(
'Worker Isolate: waiting for a task...'
)
;
// Listen for tasks sent by the main Isolate
workerReceivePort.
listen
(
(
message
)
{
if
(
message
is
List
<
int
)
{// Task received: square each number in the list
(
'Worker Isolate: received data $message'
)
;
var
result
=
message.
map
(
(
n
)
=>
n
n
)
.
toList
(
)
;
// Send the result back through mainSendPort
mainSendPort.
send
(
result
)
;
}
else
if
(
message
==
'exit'
)
{
(
'Worker Isolate: received exit signal, shutting down'
)
;
workerReceivePort.
close
(
)
;
mainSendPort.
send
(
'goodbye'
)
;
}
}
)
;
}
Future
<
void
main
(
)
async
{
print
('Main Isolate: started'
)
;
// Create the main receive port
var
mainReceivePort
=
ReceivePort
(
)
;
// Start the Worker Isolate
await Isolate.
spawn
(
workerIsolate
,
mainReceivePort.
sendPort
)
;
// Wait for the Worker to send its SendPort (to establish two-way communication)
SendPort
?
workerSendPort
;
await
for
(
var
msg
in
mainReceivePort
)
{
if
(
msg
is
SendPort
)
{
workerSendPort
=
msg
;
(
'Main Isolate: two-way communication with Worker established'
)
;
break
;
}
}
// Send a task through the Worker's SendPort
workerSendPort
!
.
send
(
[
1
,
2
,
3
,
4
,
5
]
)
;
workerSendPort.
send
(
[
10
,
20
,
30
]
)
;
// Receive the Worker's computation result
int
responseCount
=
0
;
await
for
(
var
msg
in
mainReceivePort
)
{
if
(
msg
is
List
<
int
)
{
print
('Main Isolate: received result $msg'
)
;
responseCount
++
;
if
(
responseCount
==
2
)
break
;
}
}
// Send the exit signal
workerSendPort.
send
(
'exit'
)
;
await
for
(
var
msg
in
mainReceivePort
)
{
if
(
msg
==
'goodbye'
)
{
(
'Main Isolate: Worker has exited'
)
;
break
;
}
}
mainReceivePort.
close
(
)
;
(
'RUNOOB two-way communication demo finished'
)
;
}
主 Isolate: 启动
主 Isolate: 已建立与 Worker 的双向通信
Worker Isolate: 等待任务...
Worker Isolate: 收到数据 [1, 2, 3, 4, 5]
主 Isolate: 收到结果 [1, 4, 9, 16, 25]
Worker Isolate: 收到数据 [10, 20, 30]
主 Isolate: 收到结果 [100, 400, 900]
Worker Isolate: 收到退出信号,关闭
主 Isolate: Worker 已退出
RUNOOB 双向通信演示结束
Simplify with Isolate.run (Dart 3.0+)
Dart 3.0 introduced Isolate.run(), greatly simplifying the use of one-off computation tasks.
Example
import
'dart:isolate'
;
// A time-consuming computation function
int
complexCalculation
(
int
n
)
{
int
result
=
0
;
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
result
=
i
i
;
}
return
result
;
}
Future
<
void
main
(
)
async
{
print
('Starting computation...'
)
;
// Isolate.run: done in one line, automatically creates an Isolate, executes, and returns the result
var
result
=
await Isolate.
run
(
(
)
=>
complexCalculation
(
10000000
)
)
;
(
'RUNOOB computation result: $result'
)
;
(
'Computation complete'
)
;
// Comparison: if Isolate is not used
(
'(If you compute directly in the main Isolate, it will block other operations)'
)
;
}
开始计算...
RUNOOB 计算结果: 333333283333335000000
计算完成
(如果在主 Isolate 中直接计算,会阻塞其他操作)
Isolate.run() is suited to scenarios of "performing a computation once and returning a result". If you need continuous, two-way communication (such as a long-running background service), you need to use Isolate.spawn() + SendPort/ReceivePort.
Limitations of Isolate Message Passing
| Can be passed | Cannot be passed |
|---|---|
| null, bool, int, double, String | Functions, closures |
| List, Map, Set (their elements can also be passed) | Stream, Future |
| SendPort (used to establish a communication link) | Most objects of non-primitive types |
| Capability (permission token) | File handles, network Socket |
| TransferableTypedData (efficiently transfer large chunks of data) | Custom classes (unless serializable) |
Comparison of concurrency models
| Feature | Dart Isolate | Traditional multithreading (e.g. Java) |
|---|---|---|
| Memory model | Independent memory, not shared | Shared memory |
| Communication method | Message passing (SendPort) | Shared variables + locks |
| Data races | None (no sharing) | Requires lock mechanisms for protection |
| Deadlock risk | Almost none | Exists |
| Creation overhead | Relatively large | Relatively small |
| Applicable scenarios | CPU-intensive parallel computing | General concurrency |
Although Dart's Isolate model avoids data races, the trade-off is relatively high creation and communication overhead. Do not create thousands of Isolates -- usually a few Isolates are enough. For I/O-intensive tasks, using async/await is the best choice.