Hey, is there a better way to create properties wh...
# getting-started
j
Hey, is there a better way to create properties where getters and setters are protected using a lock? private val lock = ReentrantReadWriteLock() fun getName(): String { lock.readLock().lock() try { return name } finally { lock.readLock().unlock() } }
d
jschneider: First of all, your
fun getName
should really be a
val name
with a getter. And then check out the extension functions on
ReentrantReadWriteLock
that the standard library provides: http://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/java.util.concurrent.locks.-reentrant-read-write-lock/index.html
n
so something like
Copy code
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.*

class K {
    private val lock = ReentrantReadWriteLock()
    var name = "initial"
        get() = lock.read { field }
        set(new) = lock.write { field = new }
}