Correctly implementing wait and notify in Kotlin

后端 未结 3 1997
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 11:54

According to this document, using wait and notify is discouraged in Kotlin: https://kotlinlang.org/docs/reference/java-interop.html

3条回答
  •  情话喂你
    2021-01-01 12:34

    A BlockingQueue can be a suitable high-level concurrency utility for your use case, but applying it requires knowing and modifying your code structure.

    The idea is, fetchData() should .take() an item from the queue, and if the queue is empty, that will block the execution until an item appears, which eliminates the .wait() in your code. The producer of the data should .put(t) the data into the queue.


    If you really need to use wait and notify, e.g. for implementing a concurrency utility at low-level, you can cast a Kotlin object to java.lang.Object and call these functions afterwards, as said in the language reference. Or, written as extension functions:

    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
    private fun Any.wait() = (this as java.lang.Object).wait()
    

提交回复
热议问题