Lazy initialzation bug in debug mode


#1
class Resource : Closeable {
    override fun close() {
        throw RuntimeException("Shouldn't call close!!!")
    }
}

class BaseClass {

    private val inited = AtomicBoolean(false);

    private val resource: Resource by lazy {
        inited.set(true)
        return@lazy Resource()
    }

    fun close() {
        if (inited.get()) {
            resource.close()
        }
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            BaseClass().close()
        }
    }
}

When I run this code directly, it’s always successfully. But if makes a breakpoint at if (inited.get()), it always calls resource.close(). Commet inited.set(true) or only makes breakpoint on resource.close(), it never called.

I make a breakpoint on inited.set(true), it never called , but inited.get() always return true.

I don’t know why, It’s strange.


#2

Debugger invoke methods to fill watches