import kotlin.reflect.KProperty

class BankAccount() {
    var balance: Int by Delegate()
    private var isClosed = false
    internal val lock = Any()

    fun adjustBalance(x: Int): Unit {
        synchronized(lock) {
            if (!isClosed) {
                balance += x
            } else throw IllegalStateException()
        }
    }

    fun close(): Unit {
        isClosed = true
    }

    class Delegate() {
        private var balance = 0
        operator fun getValue(thisRef: BankAccount, property: KProperty<*>): Int {
            synchronized(thisRef.lock) {
                if (thisRef.isClosed) {
                    throw IllegalStateException()
                }
                return balance
            }
        }

        operator fun setValue(thisRef: BankAccount, property: KProperty<*>, value: Int) {
            synchronized(thisRef.lock) {
                if (thisRef.isClosed) {
                    throw IllegalStateException()
                } else balance = value
            }
        }
    }

}