Hi, i'm entering deadlock when setting value with ...
# getting-started
a
Hi, i'm entering deadlock when setting value with lock inside a class property
Copy code
class CurrentServerTimestamp {
    private val lock: ReentrantLock = ReentrantLock()

    private var timestampInMillis: Long
        get() = lock.withLock { timestampInMillis }
        set(value) {
            lock.withLock { timestampInMillis = value }
        }

    init {
        timestampInMillis = CURRENT_SERVER_TIME_NOT_SET
    }

    companion object {

        private val instance = CurrentServerTimestamp()

        fun isValidTimeStamp(): Boolean {
            return instance.timestampInMillis != CURRENT_SERVER_TIME_NOT_SET
        }

        fun get(): Long = instance.timestampInMillis

        fun set(currentServerTimestamp: Long) {
            instance.timestampInMillis = currentServerTimestamp
        }
    }
}
Copy code
set(value) {
            lock.withLock { timestampInMillis = value }
        }
I think this is causing the dead lock, is there any way to over come this and still i get the intended behavior ?
e
it's not a deadlock, you've made your accessors self-recursive (which you can see if you simply put a
println
in there). if you want to access the backing field, do so explicitly:
Copy code
private var timestampInMillis: Long
     get() = lock.withLock { field }
     set(value) {
         lock.withLock { field = value }
     }
also you can initialize it like so:
Copy code
private var timestampInMillis: Long = CURRENT_SERVER_TIME_NOT_SET
    get() = ...
    set(value) { ... }
that sets the backing field directly, not going through the custom accessor, but that should be fine for this case (and most cases)
a
@ephemient thank you 🙂
saved my day