Concurrency Management in Ballerina (Lock statement)

Rajith Vitharana
Ballerina Swan Lake Tech Blog
2 min readApr 28, 2018

--

Ballerina is a general-purpose programming language which is being developed by WSO2, More details here.

We have been missing this feature in Ballerina for some time, The requirement is like, we needed a way to provide safe concurrent access to shared resources.

So how is it handled in Ballerina?..

Ballerina now have this syntax called “lock” which can be used to solve this problem

lock {
statement;+
}

So how does this work?

As the initial version, we are only going to provide locking support for global level and service level variables and we will have only one lock mode. Unlike Java(or any other language that I know of), you can use to lock multiple variables at a time using this lock statement with a simple syntax.

What happens internally is that we analyze the statements inside the lock block and identify all the global and service level variables used within that block. Then we use two-phase locking mechanism to acquire locks for those variables at the beginning of the the lock statement. Although this doesn’t totally prevent the possibility of deadlock situations, it reduces the possibility in a considerable manner.

example lock code looks like follows

You can also have nested lock statements as well, in that case, what happens is, we scope the variable locking duration to the lock block and at end of each lock block, we release acquired locks for that lock block.

example would be as follows

We track statuses of these locks for one level of function calls as well. So if you call a function within a lock statement which tries to lock the same variable, that will be possible as you already have acquired the lock for that variable. So the following example would work without any issue.

Although I have used functions to explain the behavior, the lock statement really comes in handy in service scenarios, where every request may use shared variables.

Hope I have captured here the current status of the concurrency handling support in Ballerina. There will be many improvements to come in future releases of Ballerina for these constructs.

--

--