Overview
Concurrent programming using isolates: independent workers that are similar to threads but don't share memory, communicating only via messages.
To use this library in your code:
import 'raya:isolate';Classes
class IsolateSpawnException implements Exception
Thrown when an isolate cannot be created.
Constructors
IsolateSpawnException(this.message)import 'raya:isolate';
void main() {
final e = IsolateSpawnException('entry point is not a top-level function');
print('message: ${e.message}');
print('is an Exception: ${e is Exception}');
}message: entry point is not a top-level function is an Exception: true
Properties
Methods
String toString()import 'raya:isolate';
void main() {
print(IsolateSpawnException('could not load module').toString());
}IsolateSpawnException: could not load module
Isolate
final class Isolate
An isolated Raya execution context.
All Raya code runs in an isolate, and code can access classes and values only from the same isolate. Different isolates can communicate by sending values through ports (see ReceivePort, SendPort).
An Isolate object is a reference to an isolate, usually different from the current isolate. It represents, and can be used to control, the other isolate.
When spawning a new isolate, the spawning isolate receives an Isolate object representing the new isolate when the spawn operation succeeds.
Isolates run code in its own event loop, and each event may run smaller tasks in a nested microtask queue.
An Isolate object allows other isolates to control the event loop of the isolate that it represents, and to inspect the isolate, for example by pausing the isolate or by getting events when the isolate has an uncaught error.
The controlPort identifies and gives access to controlling the isolate, and the pauseCapability and terminateCapability guard access to some control operations. For example, calling pause on an Isolate object created without a pauseCapability, has no effect.
The Isolate object provided by a spawn operation will have the control port and capabilities needed to control the isolate. New isolate objects can be created without some of these capabilities if necessary, using the Isolate.new constructor.
An Isolate object cannot be sent over a SendPort, but the control port and capabilities can be sent, and can be used to create a new functioning Isolate object in the receiving port's isolate.
Constructors
Isolate(this.controlPort, {this.pauseCapability, this.terminateCapability})Creates a new Isolate object with a restricted set of capabilities.
The port should be a control port for an isolate, as taken from another Isolate object.
The capabilities should be the subset of the capabilities that are available to the original isolate. Capabilities of an isolate are locked to that isolate, and have no effect anywhere else, so the capabilities should come from the same isolate as the control port.
Can also be used to create an Isolate object from a control port, and any available capabilities, that have been sent through a SendPort.
Example:
Isolate isolate = findSomeIsolate();
Isolate restrictedIsolate = Isolate(isolate.controlPort);
untrustedCode(restrictedIsolate);
This example creates a new Isolate object that cannot be used to pause or terminate the isolate. All the untrusted code can do is to inspect the isolate and see uncaught errors or when it terminates.
import 'raya:isolate';
void main() {
// An Isolate object is a handle around a control port; anyone holding the port can wrap it.
final self = Isolate.current;
final handle = Isolate(self.controlPort);
print('same control port: ${handle.controlPort == self.controlPort}');
print('no capabilities given: ${handle.pauseCapability == null && handle.terminateCapability == null}');
}same control port: true no capabilities given: true
Static
static const int beforeNextEvent = 1Argument to ping and kill: Ask for action before the next event.
static Future<R> run<R>(FutureOr<R> computation(), {String? debugName})Runs computation in a new isolate and returns the result.
int slowFib(int n) =>
n <= 1 ? 1 : slowFib(n - 1) + slowFib(n - 2);
// Compute without blocking current isolate.
var fib40 = await Isolate.run(() => slowFib(40));
If computation is asynchronous (returns a Future<R>) then that future is awaited in the new isolate, completing the entire asynchronous computation, before returning the result.
int slowFib(int n) =>
n <= 1 ? 1 : slowFib(n - 1) + slowFib(n - 2);
Stream<int> fibStream() async* {
for (var i = 0;; i++) yield slowFib(i);
}
// Returns `Future<int>`.
var fib40 = await Isolate.run(() => fibStream().elementAt(40));
If computation throws, the isolate is terminated and this function throws the same error.
Future<int> eventualError() async {
await Future.delayed(const Duration(seconds: 1));
throw StateError("In a bad state!");
}
try {
await Isolate.run(eventualError);
} on StateError catch (e, s) {
print(e.message); // In a bad state!
print(LineSplitter.split("$s").first); // Contains "eventualError"
}
Any uncaught asynchronous errors will terminate the computation as well, but will be reported as a RemoteError because addErrorListener does not provide the original error object.
The result is sent using exit, which means it's sent to this isolate without copying.
The computation function and its result (or error) must be sendable between isolates. Objects that cannot be sent include open files and sockets (see SendPort.send for details).
If computation is a closure then it may implicitly send unexpected state to the isolate due to limitations in the Raya implementation.
void serializeAndWrite(File f, Object o) async {
final openFile = await f.open(mode: FileMode.append);
Future writeNew() async {
// Will fail with:
// "Invalid argument(s): Illegal argument in isolate message"
// because `openFile` is captured.
final encoded = await Isolate.run(() => jsonEncode(o));
await openFile.writeString(encoded);
await openFile.flush();
await openFile.close();
}
if (await openFile.position() == 0) {
await writeNew();
}
}
In such cases, you can create a new function to call Isolate.run that takes all of the required state as arguments.
void serializeAndWrite(File f, Object o) async {
final openFile = await f.open(mode: FileMode.append);
Future writeNew() async {
Future<String> encode(o) => Isolate.run(() => jsonEncode(o));
final encoded = await encode(o);
await openFile.writeString(encoded);
await openFile.flush();
await openFile.close();
}
if (await openFile.position() == 0) {
await writeNew();
}
}
The debugName is only used to name the new isolate for debugging.
import 'raya:isolate';
int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);
Future<void> main() async {
// The computation runs on another isolate; its result is sent back.
final r = await Isolate.run(() => fib(25));
print('fib(25) computed on a worker: $r');
final words = await Isolate.run(() => 'the quick brown fox'.split(' ').map((w) => w.length).toList());
print('word lengths: $words');
}fib(25) computed on a worker: 75025 word lengths: [3, 5, 5, 3]
external static Isolate get currentAn Isolate object representing the current isolate.
The current isolate for code using current is the isolate running the code.
The isolate object provides the capabilities required to inspect, pause or kill the isolate, and allows granting these capabilities to others.
It is possible to pause the current isolate, but doing so without first passing the ability to resume it again to another isolate, is a sure way to hang your program.
external static Future<Uri?> get packageConfigThe location of the package configuration file of the current isolate.
If the isolate was spawned without specifying its package configuration file then the returned value is null.
Otherwise, the returned value is an absolute URI specifying the location of isolate's package configuration file.
The package configuration file is usually named package_config.json, and you can use [package:package_config] to read and parse it.
external static Uri? get packageConfigSyncThe location of the package configuration file of the current isolate.
If the isolate was spawned without specifying its package configuration file then the returned value is null.
Otherwise, the returned value is an absolute URI specifying the location of isolate's package configuration file.
The package configuration file is usually named package_config.json, and you can use [package:package_config] to read and parse it.
external static Future<Uri?> resolvePackageUri(Uri packageUri)Resolves a package: URI to its actual location.
Returns the actual location of the file or directory specified by the packageUri package: URI.
If the packageUri is not a package: URI, it's returned as-is.
Returns null if packageUri is a package: URI, but either the current package configuration does not have a configuration for the package name of the URI, or the URI is not valid (doesn't start with package:valid_package_name/),
A package: URI is resolved to its actual location based on a package resolution configuration (see packageConfig) which specifies how to find the actual location of the file or directory that the package: URI points to.
The actual location corresponding to a package: URI is always a non-package: URI, typically a file: or possibly http: URI.
A program may be run in a way where source files are not available, and if so, the returned URI may not correspond to the actual file or directory or be null.
import 'raya:isolate';
Future<void> main() async {
final u = await Isolate.resolvePackageUri(Uri.parse('package:riptide_numerics_stats/riptide_numerics_stats.ray'));
print('resolved scheme: ${u?.scheme}');
print('file name: ${u?.pathSegments.last}');
print('unknown package: ${await Isolate.resolvePackageUri(Uri.parse('package:no_such_pkg/x.ray'))}');
}resolved scheme: file file name: riptide_numerics_stats.ray unknown package: null
external static Uri? resolvePackageUriSync(Uri packageUri)Resolves a package: URI to its actual location.
Returns the actual location of the file or directory specified by the packageUri package: URI.
If the packageUri is not a package: URI, it's returned as-is.
Returns null if packageUri is a package: URI, but either the current package configuration does not have a configuration for the package name of the URI, or the URI is not valid (doesn't start with package:valid_package_name/),
A package: URI is resolved to its actual location based on a package resolution configuration (see packageConfig) which specifies how to find the actual location of the file or directory that the package: URI points to.
The actual location corresponding to a package: URI is always a non-package: URI, typically a file: or possibly http: URI.
A program may be run in a way where source files are not available, and if so, the returned URI may not correspond to the actual file or directory or be null.
import 'raya:isolate';
void main() {
final u = Isolate.resolvePackageUriSync(Uri.parse('package:riptide_numerics_stats/riptide_numerics_stats.ray'));
print('resolved scheme: ${u?.scheme}');
print('ends in lib/: ${u!.pathSegments.reversed.skip(1).first}');
}resolved scheme: file ends in lib/: lib
external static Future<Isolate> spawn<T>(void entryPoint(T message), T message, {bool paused = false, bool errorsAreFatal = true, SendPort? onExit, SendPort? onError, String? debugName})Spawns an isolate that shares the same code as the current isolate.
The argument entryPoint specifies the initial function to call in the spawned isolate. The entry-point function is invoked in the new isolate with message as the only argument.
The entryPoint function must be able to be called with a single argument, that is, a function which accepts at least one positional parameter and has at most one required positional parameter. The function may accept any number of optional parameters, as long as it can be called with just a single argument. If entryPoint is a closure then it may implicitly send unexpected state to the isolate due to limitations in the Raya implementation. See run for an example.
message must be sendable between isolates. Objects that cannot be sent include open files and sockets (see SendPort.send for details). Usually the initial message contains a SendPort so that the spawner and spawnee can communicate with each other.
If the paused parameter is set to true, the isolate will start up in a paused state, just before calling the entryPoint function with the message, as if by an initial call of isolate.pause(isolate.pauseCapability). To resume the isolate, call isolate.resume(isolate.pauseCapability).
If the errorsAreFatal, onExit and/or onError parameters are provided, the isolate will act as if, respectively, setErrorsFatal, addOnExitListener and addErrorListener were called with the corresponding parameter and was processed before the isolate starts running.
If debugName is provided, the spawned Isolate will be identifiable by this name in debuggers and logging.
If errorsAreFatal is omitted, the platform may choose a default behavior or inherit the current isolate's behavior.
You can also call the setErrorsFatal, addOnExitListener and addErrorListener methods on the returned isolate, but unless the isolate was started as paused, it may already have terminated before those methods can complete.
Returns a future which will complete with an Isolate instance if the spawning succeeded. It will complete with an error otherwise.
One can expect the base memory overhead of an isolate to be in the order of 30 kb.
import 'raya:isolate';
void worker((SendPort, int) args) {
final (reply, n) = args;
reply.send([for (var i = 1; i <= n; i++) i * i]);
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(worker, (port.sendPort, 5));
print('squares from the spawned isolate: ${await port.first}');
}squares from the spawned isolate: [1, 4, 9, 16, 25]
external static Future<Isolate> spawnUri(Uri uri, List<String> args, message, {bool paused = false, SendPort? onExit, SendPort? onError, bool errorsAreFatal = true, bool? checked, Map<String, String>? environment, @Deprecated('The packages/ dir is not supported in Raya') Uri? packageRoot, Uri? packageConfig, bool automaticPackageResolution = false, String? debugName})Spawns an isolate running the script file specified by uri.
Creates and spawns a new isolate that runs the Raya program which has the uri file as the entry point that provides the main method. The new isolate belongs to a new isolate group, different from the isolate group of the spawning isolate.
The isolate starts executing the top-level main function of the library with the given URI.
The target main must be callable with zero, one or two arguments. Examples:
mainmain(args)main(args, message)
When present, the parameter args is set to the provided args list. When present, the parameter message is set to the initial message. A runtime error occurs if the message argument's runtime type cannot be assigned to the second parameter of the main method.
If the paused parameter is set to true, the isolate will start up in a paused state, as if by an initial call of isolate.pause(isolate.pauseCapability). To resume the isolate, call isolate.resume(isolate.pauseCapability).
If the errorsAreFatal, onExit and/or onError parameters are provided, the isolate will act as if, respectively, setErrorsFatal, addOnExitListener and addErrorListener were called with the corresponding parameter and was processed before the isolate starts running.
You can also call the setErrorsFatal, addOnExitListener and addErrorListener methods on the returned isolate, but unless the isolate was started as paused, it may already have terminated before those methods can complete.
The checked parameter controls whether asserts are enabled in the created isolate. In a production-mode program, the parameter is ignored, and assertions are always disabled in all isolates. Otherwise if a true or false value is provided, assertions are enabled or disabled, respectively, in the created isolate. If null or no argument is provided, asserts are enabled in the created isolate if and only if they are enabled in the spawning isolate.
It may not always be possible to honor the checked parameter. If the isolate code was pre-compiled, it may not be possible to change the checked mode setting dynamically. In that case, the checked parameter is ignored.
If the packageConfig parameter is provided, then it is used to find the location of a package resolution configuration file for the spawned isolate.
If the automaticPackageResolution parameter is provided, then the location of the package sources in the spawned isolate is automatically determined.
The environment is a mapping from strings to strings which the spawned isolate uses when looking up String.fromEnvironment values. The system may add its own entries to environment as well. If environment is omitted, the spawned isolate has the same environment declarations as the spawning isolate.
WARNING: The environment parameter is not implemented on all platforms yet.
If debugName is provided, the spawned Isolate will be identifiable by this name in debuggers and logging.
Returns a future that will complete with an Isolate instance if the spawning succeeded. It will complete with an error otherwise.
import 'raya:isolate';
import 'raya:io';
Future<void> main() async {
final dir = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${dir.path}/child.ray')
..writeAsStringSync('import "raya:isolate";\n'
'void main(List<String> args, SendPort reply) => reply.send("child got \${args.join(",")}");\n');
final port = ReceivePort();
await Isolate.spawnUri(file.uri, ['a', 'b'], port.sendPort);
print(await port.first);
dir.deleteSync(recursive: true);
}child got a,b
external static Never exit([SendPort? finalMessagePort, Object? message])Terminates the current isolate synchronously.
This operation is potentially dangerous and should be used judiciously. The isolate stops operating immediately. It throws if the optional message does not adhere to the limitations on what can be sent from one isolate to another (see SendPort.send for more details). It also throws if a finalMessagePort is associated with an isolate spawned outside of current isolate group, spawned via spawnUri.
If successful, a call to this method does not return. Pending finally blocks are not executed, control flow will not go back to the event loop, scheduled asynchronous asks will never run, and even pending isolate control commands may be ignored. (The isolate will send messages to ports already registered using Isolate.addOnExitListener, but no further Raya code will run in the isolate.)
If finalMessagePort is provided, and the message can be sent through it (see SendPort.send for more details), then the message is sent through that port as the final operation of the current isolate. The isolate terminates immediately after that SendPort.send call returns.
If the port is a native port -- one provided by ReceivePort.sendPort or RawReceivePort.sendPort -- the system may be able to send this final message more efficiently than normal port communication between live isolates. In these cases this final message object graph will be reassigned to the receiving isolate without copying. Further, the receiving isolate will in most cases be able to receive the message in constant time.
import 'raya:isolate';
void worker(SendPort reply) {
final big = List.generate(1000, (i) => i);
// Ends this isolate; the list is handed over without copying.
Isolate.exit(reply, big);
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(worker, port.sendPort);
final list = await port.first as List<int>;
print('received ${list.length} items, last ${list.last}');
}received 1000 items, last 999
external static Isolate create({String? debugName})Create a new isolate in the current isolate group.
Similar to Raya_CreateIsolateInGroup Raya VM C API.
The isolate has been created, but its event loop is not running.
To start processing isolate's messages:
- Start isolate's event loop synchronously on the current thread by calling
Isolate.runEventLoopSync - Integrate isolate's event loop with an external event loop by registering event callback (
Isolate.onEvent) to forward event notifications to an external event loop and then draining pending events (Isolate.handleEvent) from that event loop.
external static bool pinToCurrentThread()Pin current isolate to the current OS thread.
Once an isolate is pinned to an OS thread it cannot be entered by any other OS thread. An attempt to acquire exclusive access to it from another thread will fail with an error.
Equivalent to Raya_SetCurrentThreadOwnsIsolate Raya VM C API.
Returns true on success and false otherwise (e.g. if target isolate is already pinned to another thread).
Properties
final SendPort controlPortControl port used to send control messages to the isolate.
The control port identifies the isolate.
An Isolate object allows sending control messages through the control port.
Some control messages require a specific capability to be passed along with the message (see pauseCapability and terminateCapability), otherwise the message is ignored by the isolate.
final Capability? pauseCapabilityCapability granting the ability to pause the isolate.
This capability is required by pause. If the capability is null, or if it is not the correct pause capability of the isolate identified by controlPort, then calls to pause will have no effect.
If the isolate is spawned in a paused state, use this capability as argument to the resume method in order to resume the paused isolate.
final Capability? terminateCapabilityCapability granting the ability to terminate the isolate.
This capability is required by kill and setErrorsFatal. If the capability is null, or if it is not the correct termination capability of the isolate identified by controlPort, then calls to those methods will have no effect.
external String? get debugNameThe name of the Isolate displayed for debug purposes.
This can be set using the debugName parameter in spawn and spawnUri.
This name does not uniquely identify an isolate. Multiple isolates in the same process may have the same debugName.
For a given isolate, this value will be the same as the values returned by Raya_DebugName in the C embedding API and the debugName property in IsolateMirror.
Stream get errorsReturns a broadcast stream of uncaught errors from the isolate.
Each error is provided as an error event on the stream.
The actual error object and stackTraces will not necessarily be the same object types as in the actual isolate, but they will always have the same Object.toString result.
This stream is based on addErrorListener and removeErrorListener.
external bool get isPinnedToCurrentThreadWhether the isolate is pinned to the current OS thread.
Equivalent to Raya_GetCurrentThreadOwnsIsolate Raya VM C API.
external void set onEvent(void Function(Isolate) callback)Event notify callback for the isolate.
Provided callback will be called once for every new event which isolate needs to react to. Pending events can be then later be drained by calling Isolate.handleEvent.
Provided callback must be deeply immutable and will be called on an arbitrary thread and not necessarily within any isolate. See NativeCallable.isolateGroupBound.
IMPORTANT: Isolate.handleEvent MUST NOT be called from the callback as this will cause a dead-locks of the Raya execution environment.
Similar to Raya_SetMessageNotifyCallback Raya VM C API.
Methods
Capability pause([Capability? resumeCapability])Requests the isolate to pause.
When the isolate receives the pause command, it stops processing events from the event loop queue. It may still add new events to the queue in response to, e.g. timers or receive-port messages. When the isolate is resumed, it starts handling the already enqueued events.
The pause request is sent through the isolate's command port, which bypasses the receiving isolate's event loop. The pause takes effect when it is received, pausing the event loop as it is at that time.
The resumeCapability is used to identity the pause, and must be used again to end the pause using resume. If resumeCapability is omitted, a new capability object is created and used instead.
If an isolate is paused more than once using the same capability, only one resume with that capability is needed to end the pause.
If an isolate is paused using more than one capability, each pause must be individually ended before the isolate resumes.
Returns the capability that must be used to end the pause. This is either resumeCapability, or a new capability when resumeCapability is omitted.
If pauseCapability is null, or it's not the pause capability of the isolate identified by controlPort, the pause request is ignored by the receiving isolate.
import 'raya:isolate';
void worker(SendPort p) => p.send('worker ran');
Future<void> main() async {
final port = ReceivePort();
final iso = await Isolate.spawn(worker, port.sendPort, paused: true);
final cap = iso.pause(iso.pauseCapability);
print('paused twice with the same capability: ${cap == iso.pauseCapability}');
iso.resume(cap);
print(await port.first);
}paused twice with the same capability: true worker ran
external void resume(Capability resumeCapability)Resumes a paused isolate.
Sends a message to an isolate requesting that it ends a pause that was previously requested.
When all active pause requests have been cancelled, the isolate will continue processing events and handling normal messages.
If the resumeCapability is not one that has previously been used to pause the isolate, or it has already been used to resume from that pause, the resume call has no effect.
import 'raya:isolate';
void worker(SendPort p) => p.send('started after resume');
Future<void> main() async {
final port = ReceivePort();
final iso = await Isolate.spawn(worker, port.sendPort, paused: true);
print('spawned paused');
iso.resume(iso.pauseCapability!);
print(await port.first);
}spawned paused started after resume
external void addOnExitListener(SendPort responsePort, {Object? response})Requests an exit message on responsePort when the isolate terminates.
The isolate will send response as a message on responsePort as the last thing before it terminates. It will run no further code after the message has been sent.
Adding the same port more than once will only cause it to receive one exit message, using the last response value that was added, and it only needs to be removed once using removeOnExitListener.
If the isolate has terminated before it can receive this request, no exit message will be sent.
The response object must follow the same restrictions as enforced by SendPort.send when sending to an isolate from another isolate group; only simple values that can be sent to all isolates, like null, booleans, numbers or strings, are allowed.
Since isolates run concurrently, it's possible for it to exit before the exit listener is established, and in that case no response will be sent on responsePort. To avoid this, either use the corresponding parameter to the spawn function, or start the isolate paused, add the listener and then resume the isolate.
import 'raya:isolate';
void worker(int n) {}
Future<void> main() async {
final exits = ReceivePort();
final iso = await Isolate.spawn(worker, 0, paused: true);
iso.addOnExitListener(exits.sendPort, response: 'worker exited');
iso.resume(iso.pauseCapability!);
print(await exits.first);
}worker exited
external void removeOnExitListener(SendPort responsePort)Stops listening for exit messages from the isolate.
Requests for the isolate to not send exit messages on responsePort. If the isolate isn't expecting to send exit messages on responsePort, because the port hasn't been added using addOnExitListener, or because it has already been removed, the request is ignored.
If the same port has been passed via addOnExitListener more than once, only one call to removeOnExitListener is needed to stop it from receiving exit messages.
Closing the receive port that is associated with the responsePort does not stop the isolate from sending uncaught errors, they are just going to be lost.
An exit message may still be sent if the isolate terminates before this request is received and processed.
import 'raya:isolate';
void worker(SendPort done) => done.send('worker finished');
Future<void> main() async {
final exits = ReceivePort(), done = ReceivePort();
final iso = await Isolate.spawn(worker, done.sendPort, paused: true);
iso.addOnExitListener(exits.sendPort, response: 'exit');
iso.removeOnExitListener(exits.sendPort);
iso.resume(iso.pauseCapability!);
print(await done.first);
final got = await exits.first.timeout(const Duration(milliseconds: 200), onTimeout: () => 'none');
print('exit message after removing the listener: $got');
exits.close();
}worker finished exit message after removing the listener: none
external void setErrorsFatal(bool errorsAreFatal)Sets whether uncaught errors will terminate the isolate.
If errors are fatal, any uncaught error will terminate the isolate event loop and shut down the isolate.
This call requires the terminateCapability for the isolate. If the capability is absent or incorrect, no change is made.
Since isolates run concurrently, it's possible for the receiving isolate to exit due to an error, before a request, using this method, has been received and processed. To avoid this, either use the corresponding parameter to the spawn function, or start the isolate paused, set errors non-fatal and then resume the isolate.
import 'raya:isolate';
import 'raya:async';
void worker(SendPort done) {
Timer.run(() => throw StateError('first'));
Timer(const Duration(milliseconds: 20), () => done.send('still alive after the error'));
}
Future<void> main() async {
final done = ReceivePort(), errors = ReceivePort();
final iso = await Isolate.spawn(worker, done.sendPort, paused: true, errorsAreFatal: true);
iso.setErrorsFatal(false);
iso.addErrorListener(errors.sendPort);
iso.resume(iso.pauseCapability!);
print('error reported: ${(await errors.first as List).first}');
print(await done.first);
}error reported: Bad state: first still alive after the error
external void kill({int priority = beforeNextEvent})Requests the isolate to shut down.
The isolate is requested to terminate itself. The priority argument specifies when this must happen.
The priority, when provided, must be one of immediate or beforeNextEvent (the default). The shutdown is performed at different times depending on the priority:
immediate: The isolate shuts down as soon as possible. Control messages are handled in order, so all previously sent control events from this isolate will all have been processed. The shutdown should happen no later than if sent withbeforeNextEvent. It may happen earlier if the system has a way to shut down cleanly at an earlier time, even during the execution of another event.beforeNextEvent: The shutdown is scheduled for the next time control returns to the event loop of the receiving isolate, after the current event, and any already scheduled control events, are completed.
If terminateCapability is null, or it's not the terminate capability of the isolate identified by controlPort, the kill request is ignored by the receiving isolate.
import 'raya:isolate';
void worker(SendPort p) {
while (true) {}
}
Future<void> main() async {
final exits = ReceivePort();
final iso = await Isolate.spawn(worker, exits.sendPort, onExit: exits.sendPort);
iso.kill(priority: Isolate.immediate);
print('killed; onExit delivered: ${await exits.first} (the default response)');
}killed; onExit delivered: null (the default response)
external void ping(SendPort responsePort, {Object? response, int priority = immediate})Requests that the isolate send response on the responsePort.
The response object must follow the same restrictions as enforced by SendPort.send when sending to an isolate from another isolate group; only simple values that can be sent to all isolates, like null, booleans, numbers or strings, are allowed.
If the isolate is alive, it will eventually send response (defaulting to null) on the response port.
The priority must be one of immediate or beforeNextEvent. The response is sent at different times depending on the ping type:
immediate: The isolate responds as soon as it receives the control message. This is after any previous control message from the same isolate has been received and processed, but may be during execution of another event.beforeNextEvent: The response is scheduled for the next time control returns to the event loop of the receiving isolate, after the current event, and any already scheduled control events, are completed.
import 'raya:isolate';
void worker(int _) {}
Future<void> main() async {
final pong = ReceivePort();
final iso = await Isolate.spawn(worker, 0, paused: true);
// Ping is answered even while the isolate is paused.
iso.ping(pong.sendPort, response: 'pong', priority: Isolate.immediate);
print(await pong.first);
iso.kill();
}pong
external void addErrorListener(SendPort port)Requests that uncaught errors of the isolate are sent back to port.
The errors are sent back as two-element lists. The first element is a String representation of the error, usually created by calling toString on the error. The second element is a String representation of an accompanying stack trace, or null if no stack trace was provided. To convert this back to a StackTrace object, use StackTrace.fromString.
Listening using the same port more than once does nothing. A port will only receive each error once, and will only need to be removed once using removeErrorListener.
Closing the receive port that is associated with the port does not stop the isolate from sending uncaught errors, they are just going to be lost. Instead use removeErrorListener to stop receiving errors on port.
Since isolates run concurrently, it's possible for it to exit before the error listener is established. To avoid this, start the isolate paused, add the listener and then resume the isolate.
import 'raya:isolate';
void worker(int n) => throw ArgumentError('bad n: $n');
Future<void> main() async {
final errors = ReceivePort();
final iso = await Isolate.spawn(worker, 7, paused: true);
iso.addErrorListener(errors.sendPort);
iso.resume(iso.pauseCapability!);
final pair = await errors.first as List;
print('error: ${pair[0]}');
print('stack is sent as text: ${pair[1] is String}');
}error: Invalid argument(s): bad n: 7 stack is sent as text: true
external void removeErrorListener(SendPort port)Stops listening for uncaught errors from the isolate.
Requests for the isolate to not send uncaught errors on port. If the isolate isn't expecting to send uncaught errors on port, because the port hasn't been added using addErrorListener, or because it has already been removed, the request is ignored.
If the same port has been passed via addErrorListener more than once, only one call to removeErrorListener is needed to stop it from receiving uncaught errors.
Uncaught errors message may still be sent by the isolate until this request is received and processed.
import 'raya:isolate';
void worker(SendPort done) {
done.send('ok');
}
Future<void> main() async {
final errors = ReceivePort(), done = ReceivePort();
final iso = await Isolate.spawn(worker, done.sendPort, paused: true);
iso.addErrorListener(errors.sendPort);
iso.removeErrorListener(errors.sendPort);
iso.resume(iso.pauseCapability!);
print('worker said ${await done.first}; listener removed before it ran');
errors.close();
}worker said ok; listener removed before it ran
external R runSync<R>(R Function() f)Execute the given function in the context of the given isolate.
This function will throw if target isolate is running.
Throws an error if target isolate is pinned to another thread and thus can't be entered from this thread. See pinToCurrentThread and isPinnedToCurrentThread.
Throws an error if the target isolate belongs to another isolate group.
Throws an error if f is not deeply immutable.
Throws an error if result returned by f is not deeply immutable.
external void shutdownSync()Shut down target isolate.
Shutting down the isolate stops its event loop without processing any pending messages and closes all open receive ports owned by the isolate.
This function will block until it acquires exclusive access to the target isolate. Isolate can only be entered for synchronous execution between turns of its event loop, when no other thread is executing code in the target isolate.
external void runEventLoopSync()Run event loop for the target isolate synchronously on the current thread.
This function will block until it acquires exclusive access to the target isolate. Isolate can only be entered for synchronous execution between turns of its event loop, when no other thread is executing code in the target isolate.
This function will return once the isolate has no open keep-alive receive ports.
The isolate will be marked as pinned to the current thread.
Similar to Raya_RunLoop Raya VM C API, but unlike Raya_RunLoop this function executes isolate's event loop on the current thread instead of delegating it into the thread-pool.
Throws an error if target isolate is pinned to another thread or already has an event loop running.
external void handleEvent()Handle at most one pending event for the isolate.
This function does nothing if there are no pending events.
This function will block until it acquires exclusive access to the target isolate. Isolate can only be entered for synchronous execution between turns of its event loop, when no other thread is executing code in the target isolate.
Similar to Raya_HandleMessage Raya VM C API.
SendPort
abstract interface class SendPort implements Capability
Sends messages to its ReceivePorts.
SendPorts are created from ReceivePorts. Any message sent through a SendPort is delivered to its corresponding ReceivePort. There might be many SendPorts for the same ReceivePort.
SendPorts can be transmitted to other isolates, and they preserve equality when sent.
Properties
int get hashCodeA hash code for this send port that is consistent with the == operator.
Methods
void send(Object? message)Sends an asynchronous message through this send port, to its corresponding ReceivePort.
If the sending and receiving isolates do not share the same code (an isolate created using Isolate.spawnUri does not share the code of the isolate that spawned it), the transitive object graph of message can only contain the following kinds of objects:
nulltrueandfalse- Instances of
int,double,String - Instances created through list, map and set literals
- Instances created by constructors of:
SendPortinstances fromReceivePort.sendPortorRawReceivePort.sendPortwhere the receive ports are created using those classes' constructors.- Instances of
Typerepresenting one of the types mentioned above,Object,dynamic,voidandNeveras well as nullable variants of all these types. For generic types type arguments must be sendable types for the whole type to be sendable.
If the sender and receiver isolate share the same code (e.g. isolates created via Isolate.spawn), the transitive object graph of message can contain any object, with the following exceptions:
- Objects with native resources (subclasses of e.g.
NativeFieldWrapperClass1). ASocketobject for example refers internally to objects that have native resources attached and can therefore not be sent. ReceivePortDynamicLibraryFinalizableFinalizerNativeFinalizerUserTagMirrorReference
Instances of classes that either themselves are marked with @pragma('vm:isolate-unsendable'), extend or implement such classes cannot be sent through the ports.
Apart from those exceptions any object can be sent. Objects that are identified as immutable (e.g. strings) will be shared whereas all other objects will be copied.
The send happens immediately and may have a linear time cost to copy the transitive object graph. The send itself doesn't block (i.e. doesn't wait until the receiver has received the message). The corresponding receive port can receive the message as soon as its isolate's event loop is ready to deliver it, independently of what the sending isolate is doing.
Note: Due to an implementation choice the Raya VM made for how closures represent captured state, closures can currently capture more state than they need, which can cause the transitive closure to be larger than needed.
import 'raya:isolate';
void echo(SendPort reply) {
final inbox = ReceivePort();
reply.send(inbox.sendPort);
inbox.listen((msg) {
reply.send('echo: $msg');
if (msg == 'bye') inbox.close();
});
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(echo, port.sendPort);
final messages = port.asBroadcastStream();
final SendPort toWorker = await messages.first;
toWorker.send('hello');
print(await messages.first);
toWorker.send('bye');
print(await messages.first);
port.close();
}echo: hello echo: bye
Operators
bool operator ==(other)Tests whether other is a SendPort pointing to the same ReceivePort as this one.
import 'raya:isolate';
void main() {
final a = ReceivePort(), b = ReceivePort();
print('same port: ${a.sendPort == a.sendPort}');
print('different ports: ${a.sendPort == b.sendPort}');
a.close();
b.close();
}same port: true different ports: false
ReceivePort
abstract interface class ReceivePort implements Stream<dynamic>
Together with SendPort, the only means of communication between isolates.
ReceivePorts have a sendPort getter which returns a SendPort. Any message that is sent through this SendPort is delivered to the ReceivePort it has been created from. There, the message is dispatched to the ReceivePort's listener.
A ReceivePort is a non-broadcast stream. This means that it buffers incoming messages until a listener is registered. Only one listener can receive messages. See Stream.asBroadcastStream for transforming the port to a broadcast stream.
A ReceivePort may have many SendPorts.
Constructors
external factory ReceivePort([String debugName = ''])Opens a long-lived port for receiving messages.
A ReceivePort is a non-broadcast stream. This means that it buffers incoming messages until a listener is registered. Only one listener can receive messages. See Stream.asBroadcastStream for transforming the port to a broadcast stream.
The optional debugName parameter can be set to associate a name with this port that can be displayed in tooling.
A receive port is closed by canceling its subscription.
import 'raya:isolate';
Future<void> main() async {
final port = ReceivePort('inbox');
port.sendPort.send(1);
port.sendPort.send(2);
print('first two messages: ${await port.take(2).toList()}');
}first two messages: [1, 2]
external factory ReceivePort.fromRawReceivePort(RawReceivePort rawPort)Creates a ReceivePort from a RawReceivePort.
The handler of the given rawPort is overwritten during the construction of the result.
import 'raya:isolate';
Future<void> main() async {
final raw = RawReceivePort();
final port = ReceivePort.fromRawReceivePort(raw);
raw.sendPort.send('via the raw port');
print(await port.first);
}via the raw port
Properties
Methods
StreamSubscription<dynamic> listen(void onData(message)?, {Function? onError, void onDone()?, bool? cancelOnError})Listen for events from Stream.
See Stream.listen.
Note that onError and cancelOnError are ignored since a ReceivePort will never receive an error.
The onDone handler will be called when the stream closes. The stream closes when close is called.
import 'raya:isolate';
void main() {
final port = ReceivePort();
var n = 0;
port.listen((msg) {
print('got $msg');
if (++n == 3) port.close();
}, onDone: () => print('port closed'));
for (final m in ['a', 'b', 'c']) {
port.sendPort.send(m);
}
}got a got b got c port closed
void close()Closes the receive port.
No further events will be received by the receive port, or emitted as stream events.
If listen has been called and the StreamSubscription has not been canceled yet, the subscription will be closed with a "done" event.
If the stream has already been canceled this method has no effect.
import 'raya:isolate';
Future<void> main() async {
final port = ReceivePort();
port.sendPort.send('kept');
final first = await port.first; // first also closes the port
print('first: $first');
final other = ReceivePort();
other.close();
print('messages after close: ${await other.toList()}');
}first: kept messages after close: []
RawReceivePort
abstract interface class RawReceivePort
A low-level asynchronous message receiver.
A RawReceivePort is low level feature, and is not Zone aware. The handler will always be invoked in the Zone.root zone.
The port cannot be paused. The data-handler must be set before the first message is received, otherwise the message is lost.
Messages can be sent to this port using sendPort.
Constructors
external factory RawReceivePort([Function? handler, String debugName = ''])Opens a long-lived port for receiving messages.
A RawReceivePort is low level and does not work with Zones. It cannot be paused. The data-handler must be set before the first message is received, otherwise the message is lost.
If handler is provided, it's set as the RawReceivePort.handler.
The optional debugName parameter can be set to associate a name with this port that can be displayed in tooling.
import 'raya:isolate';
void main() {
late RawReceivePort raw;
raw = RawReceivePort((Object? msg) {
print('handler got $msg');
raw.close();
});
raw.sendPort.send('ping');
}handler got ping
Properties
void set handler(Function? newHandler)Sets the handler that is invoked for every incoming message.
The handler is invoked in the Zone.root zone. If the handler should be invoked in the current zone, do:
rawPort.handler = Zone.current.bindCallback(actualHandler);
The handler must be a function which can accept one argument of the type of the messages sent to this port. This means that if it is known that messages will all be Strings, a handler of type void Function(String) can be used. The function is invoked dynamically with the actual messages, and if this invocation fails, the error becomes a top-level uncaught error in the Zone.root zone.
import 'raya:isolate';
void main() {
final raw = RawReceivePort();
var count = 0;
raw.handler = (Object? msg) {
print('message ${++count}: $msg');
if (count == 2) raw.close();
};
raw.sendPort.send('one');
raw.sendPort.send('two');
}message 1: one message 2: two
abstract bool keepIsolateAliveWhether this RawReceivePort keeps its Isolate alive.
By default, receive ports keep the Isolate that created them alive until close is called. If keepIsolateAlive is set to false, the isolate may close while the port is still open. The port is closed when the isolate closes, and further messages sent by the sendPort are ignored.
Methods
void close()Closes the port.
After a call to this method, any incoming message is silently dropped. The handler will never be called again.
import 'raya:isolate';
void main() {
final raw = RawReceivePort((_) => print('never called'));
raw.close();
raw.sendPort.send('dropped');
print('closed; the message is dropped and the program can exit');
}closed; the message is dropped and the program can exit
RemoteError
final class RemoteError implements Error
Description of an error from another isolate.
This error has the same toString and stackTrace.toString behavior as the original error, but has no other features of the original error.
Constructors
RemoteError(String description, String stackDescription)import 'raya:isolate';
void main() {
final e = RemoteError('connection lost', '#0 worker (worker.ray:4)');
print('description: $e');
print('stack: ${e.stackTrace}');
}description: connection lost stack: #0 worker (worker.ray:4)
Properties
final StackTrace stackTraceMethods
String toString()import 'raya:isolate';
Future<void> main() async {
try {
await Isolate.run<int>(() => throw StateError('worker failed'));
} on StateError catch (e) {
print('Isolate.run rethrows the original error: ${e.message}');
}
print(RemoteError('remote failure', '').toString());
}Isolate.run rethrows the original error: worker failed remote failure
abstract final class TransferableTypedData
An efficiently transferable sequence of byte values.
A TransferableTypedData is created from a number of bytes. This will take time proportional to the number of bytes.
The TransferableTypedData can be moved between isolates, so sending it through a send port will only take constant time.
When sent this way, the local transferable can no longer be materialized, and the received object is now the only way to materialize the data.
Constructors
external factory TransferableTypedData.fromList(List<TypedData> list)Creates a new TransferableTypedData containing the bytes of list.
It must be possible to create a single Uint8List containing the bytes, so if there are more bytes than what the platform allows in a single Uint8List, then creation fails.
import 'raya:isolate';
import 'raya:typed_data';
void sum(SendPort reply) {
final inbox = ReceivePort();
reply.send(inbox.sendPort);
inbox.first.then((t) {
final bytes = (t as TransferableTypedData).materialize().asUint8List();
reply.send(bytes.fold<int>(0, (a, b) => a + b));
});
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(sum, port.sendPort);
final msgs = port.asBroadcastStream();
final SendPort worker = await msgs.first;
worker.send(TransferableTypedData.fromList([Uint8List.fromList([1, 2, 3]), Uint8List.fromList([4, 5])]));
print('sum of transferred bytes: ${await msgs.first}');
port.close();
}sum of transferred bytes: 15
Methods
ByteBuffer materialize()Creates a new ByteBuffer containing the bytes stored in this TransferableTypedData.
The TransferableTypedData is a cross-isolate single-use resource. This method must not be called more than once on the same underlying transferable bytes, even if the calls occur in different isolates.
import 'raya:isolate';
import 'raya:typed_data';
void main() {
final t = TransferableTypedData.fromList([Uint8List.fromList([1, 2]), Int16List.fromList([256])]);
final buffer = t.materialize();
print('bytes: ${buffer.asUint8List()}');
try {
t.materialize();
} on ArgumentError {
print('second materialize: ArgumentError (it can be used once)');
}
}bytes: [1, 2, 0, 1] second materialize: ArgumentError (it can be used once)
Capability
abstract interface class Capability
An unforgeable object that comes back as equal when passed through other isolates.
Sending a capability object to another isolate, and getting it back, will produce an object that is equal to the original. There is no other way to create objects equal to a capability object.
Capabilities can be used as access guards. An isolate can receive requests for operations from other isolates, but only allow them if the request contains the correct capability object. This allows exposing the same interface to multiple clients, but restricting some operations to only those clients that have also been given the corresponding capability.
Capabilities can be used inside a single isolate, but they have no advantage over just using Object to create a unique object, and it offers no real security against other code running in the same isolate.
Constructors
external factory Capability()Create a new unforgeable capability object.
import 'raya:isolate';
void main() {
final a = Capability(), b = Capability();
print('a == a: ${a == a}');
print('a == b: ${a == b} (each capability is unique)');
}a == a: true a == b: false (each capability is unique)