import ballerina/io;

// Initializes an `isolated` variable using
// an `isolated` expression.
isolated int[] stack = [];

isolated function push(int n) {
    // Accesses `isolated` variable within a
    // `lock` statement.
    lock {
        stack.push(n);
    }

}

isolated function pop() returns int {
    lock {
        return stack.pop();
    }
}

public function main() {
    push(10);
    push(20);
    io:println(pop());
}

Isolated Variables

When a variable is declared as isolated, compiler guarantees that it is an isolated root and accessed only within a lock statement. An isolated variable declaration must be at module-level, not public, and initialized with an isolated expression. A lock statement that accesses an isolated variable must maintain isolated root invariant:

  • access only one isolated variable
  • access only one isolated variable
  • call only isolated functions
  • transfers of values in and out must use isolated expressions


The isolated functions are allowed to access isolated module-level variables, provided they follow the above rules.

import ballerina/io;
isolated int[] stack = [];

Initializes an isolated variable using an isolated expression.

isolated function push(int n) {
    lock {
        stack.push(n);
    }

Accesses isolated variable within a lock statement.

}
isolated function pop() returns int {
    lock {
        return stack.pop();
    }
}
public function main() {
    push(10);
    push(20);
    io:println(pop());
}
bal run isolated_variables.bal
20