Is thread limit annotation a good idea?


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:

var i;

fun proc() {

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


What’s the gain compared to synchronized with this annotation?

And what’s the use-case for an object to be bound to only a specific thread? What happens when another thread tries to call this method?


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.


Thank you for reply. I just try to find some better parellel programming method indeed.


It will just bloat the code with these annotations, it will be less readable if any.


Watch for agent/actor model to incapsulate thread local variables