diff --git a/docs/topics/jvm/java-interop.md b/docs/topics/jvm/java-interop.md index 10091d5754f..19d12427ce6 100644 --- a/docs/topics/jvm/java-interop.md +++ b/docs/topics/jvm/java-interop.md @@ -687,10 +687,46 @@ so to make other members of `java.lang.Object` available, Kotlin uses [extension ### wait()/notify() Methods `wait()` and `notify()` are not available on references of type `Any`. Their usage is generally discouraged in -favor of `java.util.concurrent`. If you really need to call these methods, you can cast to `java.lang.Object`: +favor of `java.util.concurrent`. + +If you have to call these methods, cast to `java.lang.Object` and suppress the warning: ```kotlin -(foo as java.lang.Object).wait() +import java.util.LinkedList + +class SimpleBlockingQueue(private val capacity: Int) { + private val queue = LinkedList() + + // java.lang.Object is used specifically to access wait() and notify() + // In Kotlin, the standard 'Any' type does not expose these methods. + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") + private val lock = Object() + + fun put(item: T) { + synchronized(lock) { + while (queue.size >= capacity) { + lock.wait() + } + queue.add(item) + println("Produced: $item") + + lock.notifyAll() + } + } + + fun take(): T { + synchronized(lock) { + while (queue.isEmpty()) { + lock.wait() + } + val item = queue.removeFirst() + println("Consumed: $item") + + lock.notifyAll() + return item + } + } +} ``` ### getClass()