Skip to content

Conversation

@danil-pavlov
Copy link
Contributor

@danil-pavlov danil-pavlov commented Dec 4, 2025

This PR updates the workaround for wait() and notify() on references of type Any with error-suppression annotation (KT-81586)

@danil-pavlov danil-pavlov requested a review from a team as a code owner December 4, 2025 13:18
@danil-pavlov danil-pavlov requested a review from KvanTTT December 5, 2025 13:24
Comment on lines 695 to 701
fun main() {
val any = Any()
synchronized(any) {
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
(any as java.lang.Object).wait()
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd change the example to something more realistic:

import java.util.LinkedList

class SimpleBlockingQueue<T>(private val capacity: Int) {
    private val queue = LinkedList<T>()

    // We use java.lang.Object 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
        }
    }
}

Or just use the single-line code snippet:

@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
(foo as java.lang.Object).wait()

The code from your example also causes a dead lock: the execution being frozen completely because there is no notify call.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A real-life example is definitely better for the docs, thank you for the suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants