s1m0nw1
s1m0nw1

Reputation: 81899

Kotlin Concurrency: Any standard function to run code in a Lock?

I've been searching for a function that takes an object of type Lock and runs a block of code with that lock taking care of locking and also unlocking.

I'd implement it as follows:

fun <T : Lock> T.runLocked(block: () -> Unit) {
    lock()
    try {
        block()
    } finally {
        unlock()
    }
}

Used like this:

val l = ReentrantLock()
l.runLocked {
    println(l.isLocked)
}

println(l.isLocked)
//true
//false

Anything available like this? I could only find the synchronized function which cannot be used like this.

Upvotes: 1

Views: 1357

Answers (1)

zsmb13
zsmb13

Reputation: 89548

You are looking for withLock, which has the exact implementation you've written yourself, except it has a generic parameter for the result of the block instead of the receiver type.

You can find other concurrency related methods of the standard library here, in the kotlin.concurrent package.

Upvotes: 4

Related Questions