Skip to content

Instantly share code, notes, and snippets.

@inikolaev
Created November 22, 2018 10:31
Show Gist options
  • Save inikolaev/2659e0213a5a087fcddee223a3d4e5fd to your computer and use it in GitHub Desktop.
Save inikolaev/2659e0213a5a087fcddee223a3d4e5fd to your computer and use it in GitHub Desktop.
Demonstration of write lock with upgrade in Kotlin
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
fun lockWithoutUpgrade() {
val lock = ReentrantReadWriteLock()
println("Acquire read lock")
lock.readLock().lock()
println("Inside read lock")
println("Acquire write lock")
lock.writeLock().lock()
println("Inside write lock")
lock.writeLock().unlock()
println("Released write lock")
lock.readLock().unlock()
println("Released read lock")
}
fun lockWithUpgrade() {
val lock = ReentrantReadWriteLock()
println("Acquire read lock")
lock.read {
println("Inside read lock")
println("Acquire write lock")
lock.write {
println("Inside write lock")
}
println("Released write lock")
}
println("Released read lock")
}
fun main(args: Array<String>) {
lockWithUpgrade()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment