kotlinsynchronizationmutexcoroutinereentrantlock

kotlin object lock


I want to use synchronized(object lock) at Kotlin, but idk how to use synchronized at Kotlin. I already search for the usage of synchronizing at Kotlin but ReentrantLock can't lock objects that I guess. please help me I am stuck with this 2 days ago.

    override fun run() {
        var active = false
        while (true) {
            while (queue.isEmpty()) {
                if (!running) {
                    return
                }
                synchronized(this) {
                    try {
                        active = false
                        wait() //<< here's error

                    } catch (e: InterruptedException) {
                        LogUtils.getLogger()
                            .log(Level.SEVERE, "There was a exception with SQL")
                        LogUtils.logThrowable(e)
                    }
                }
            }
            if (!active) {
                con.refresh()
                active = true
            }
            val rec = queue.poll()
            con.updateSQL(rec.getType(), *rec.getArgs())
        }
    }

    /**
     * Adds new record to the queue, where it will be saved to the database.
     *
     * @param rec Record to save
     */
    fun add(rec: Record) {
        synchronized(this) {
            queue.add(rec)
            notifyAll() //<< here's too
        }
    }

    /**
     * Ends this saver's job, letting it save all remaining data.
     */
    fun end() {
        synchronized(this) {
            running = false
            notifyAll() //<< and here
        }
    }```

Solution

  • Well, the solution mentioned in Correctly implementing wait and notify in Kotlin will work here. Replacing wait() //<< here's error with (this as Object).work() and notifyAll() //<< and here with (this as Object).notifyAll() will lead to behavior that is identical to Java's one.