Proper execution of waiting and notification in Kotlin

According to this document, Kotlin is not recommended to use waitand notify: https://kotlinlang.org/docs/reference/java-interop.html

waiting () / Notify ()

Effective Java article 69 kindly suggests preferring concurrency utilities for wait () and notify (). Thus, these methods are not available on links of type Any.

However, the document does not offer the correct way to execute it.

Basically, I would like to implement a service that will read the input data and process it. If there was no input, it paused until someone announced that there was new input. Sort of

while (true) {
    val data = fetchData()
    processData(data)
    if (data.isEmpty()) {
        wait()
    }
}

EDIT:

(antipatterns), , .

fetchData , .

+4
2

A BlockingQueue concurrency , .

, fetchData() .take() , , , .wait() . .put(t) .


wait notify, . concurrency Kotlin java.lang.Object , . , :

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

concurrency, .

, , ReentrantLock Condition .

, Java :

private Object lock = new Object();

synchronized(lock) {
    ...
    lock.wait();
    ...
    lock.notify();
    ...
    lock.notifyAll();
    ...
}

Kotlin:

private val lock = new ReentrantLock()
private val condition = lock.newCondtion()

lock.lock()
try {
    ...
    condition.await()     // like wait()
    ...
    condition.signal()    // like notify()
    ...
    condition.signalAll() // like notifyAll()
    ...
} finally {
    lock.unlock()
}

, , , ( ReentrantReadWriteLock.ReadLock ReentrantReadWriteLock.WriteLock).

0

Source: https://habr.com/ru/post/1679452/


All Articles