为什么Kotlin中没有并发关键字? [英] Why there are no concurrency keywords in Kotlin?

查看:442
本文介绍了为什么Kotlin中没有并发关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why there are no keywords for synchronization/concurrency?

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

So far my research gives me one solution, you wrap some high level classes and use them to handle concurrency.

考虑到纯Kotlin中的一个项目,如果需要一个小型的高度优化的组件来处理并发等,该怎么办?

Given a project in pure Kotlin, what one shall do if there is a need for a small highly optimized component that handles concurrency etc?

我的印象是Kotlin是Java的辅助语言,可以用Kotlin编写90%的代码,但是有一些用Kotlin无法表达的Java代码。

My impression is that Kotlin is an assisting language for Java, to write 90% of the code in Kotlin but have some java code that is not possible to express with Kotlin.

这是对的吗?

推荐答案

带有协程的Kotlin 1.1已发布,它带来了 async..await !在 Kotlin参考文档 Kotlinx协程库,其深度 Couroutines示例

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

在Kotlin协程之外,您有以下选择:

  • the Kovenant library adds Promises to Kotlin
  • the Quasar library provides light-weight threads and continuations
  • @Synchronized and @Volatile annotations which map directly to the same keywords in Java
  • synchronized blocks which in Kotlin come from an inline function synchronized().
  • Kotlin has a Kotlin.concurrent package and extensions with new functions and also extensions to JDK classes.
  • you can access anything in the java.util.concurrent package such as ConcurrentHashMap, CountdownLatch, CyclicBarrier, Semaphore, ...
  • you can access anything in the java.util.concurrent.locks package and Kotlin has extensions for a few of these including the cool withLock() extension function and similar read/write extensions for ReentrantReadWriteLock.
  • you can access anything in the java.util.concurrent.atomic package such as AtomicReference, AtomicLong, ...
  • you can use wait and notify on objects

您拥有Java拥有的所有东西以及更多。上面的列表满足了您的同步和锁定 短语,因此您拥有更多的语言,而且无需更改语言。任何语言功能都只会使其更漂亮。

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.

因此,您可以使用小型Kotlin运行时,JDK中的JVM运行时以及您要使用的任何其他JVM库获得100%的Kotlin代码。不需要Java代码,只需要Java(作为JVM)库。

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.

一些功能的快速示例:

class SomethingSyncd {
    @Synchronized fun syncFoo() {

    }

    val myLock = Any()

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

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

这篇关于为什么Kotlin中没有并发关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆