为什么 Kotlin 没有并发关键字?

为什么没有用于同步和并发的关键字?

到目前为止,我的研究给了我一个解决方案,您可以包装一些高级类,并使用它们来处理并发性。

给定一个纯 Kotlin 的项目,如果需要一个小型的、高度优化的、以线程安全的方式处理并发的组件,应该怎么做?

我的印象是,Kotlin 是 Java 的一种辅助语言,在 Kotlin 编写90% 的代码,但有些 Java 代码是不可能用 Kotlin 来表达的。

这样对吗? 这是原本的计划吗?

65862 次浏览

Kotlin 1.1 with Coroutines was released and it brings with it async..await! Read more about it in Kotlin reference docs, Kotlinx Coroutines library and this great in depth Couroutines by Example

Outside of the Kotlin Coroutines, you have these options:

You have everything Java has and more. Your phrase "synchronization and locks" is satisfied by the list above, and then you have even more and without language changes. Any language features would only make it a bit prettier.

So you can have 100% Kotlin code, using the small Kotlin runtime, the JVM runtime from the JDK, and any other JVM library you want to use. No need for Java code, just Java (as-in JVM) libraries.

A quick sample of some features:

class SomethingSyncd {
@Synchronized fun syncFoo() {
        

}
    

val myLock = Any()
    

fun foo() {
synchronized(myLock) {
// ... code
}
}
    

@Volatile var thing = mapOf(...)
}

I'll answer my own question since actual answer to my question was somewhere deep in kotlin discussions.

What confused me at the time coming from Java was that concurrency keywords were not language keywords they were annotations? to me it seemed strange that important concepts like synchronization were handled through annotations, but now it makes perfect sense. Kotlin is going in the direction of being a platform agnostic language, it's not going to only work on JVM but pretty much anything. So synchronized and volatile were very specific to JVM, they might not be needed in javascript for example.

In a nutshell Kotlin has everything Java has (except package visibility) and much more, a huge difference that no other language has is coroutines. But there is nothing you can write in Java that you cant do in Kotlin... (as far as I am aware)

I think suspend is a concurrency keyword:

fun main() = runBlocking {
launch { doSomething() }
}


suspend fun doSomething() {
delay(1_000)
println("Something was done")
}