https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

althaf

10/11/2021, 8:57 AM
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

ephemient

10/11/2021, 9:02 AM
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

althaf

10/11/2021, 9:18 AM
@ephemient thank you 🙂
saved my day
2 Views