Recently I used kotlin to develop a multithread program. While struggling, I thought if I can limit function/object is using only in one thread, then I would avoid a lot of mistakes. I believe compiler surely have the ablility. The syntax maybe like this:
@ThreadConstraint("mythread")
var i;
@ThreadConstraint("mythread")
fun proc() {
i++;
}
fun main(args: Array<String>) {
thread(name="mythread", block=::proc)
}
I believe there’s already some similar analysis in compiler, because synchronized function can be optimised lock free
This kind of analysis is basically an unsolved research problem; while there are certain approaches that can achieve some useful results, this kind of analysis doesn’t exist in the Kotlin compiler today, and adding it will require a large amount of research, design and implementation work.
Removing locks from synchronized blocks is performed by HotSpot, not by the Kotlin compiler, and it requires much simpler analysis.
Such methods can not be called in other thread, compiler will reject it.
In one hand, I can make my multithread code more readable and clear ( orgnizing stateful objects better ); In the other, locks can be omitted to gain performance.