Mutex
- Allows only one thread a access a resource at a time
- Provide
lock()
andunlock()
functionalities
import kotlinx.coroutines.sync.Mutex
val mutex = Mutex()
suspend fun accessSharedResource() {
mutex.lock()
try {
// access shared resource
} finally {
mutex.unlock()
}
}
Reentrant Lock
- Like a mutex lock, but with the added flexibility for a thread to repeatedly acquire (nested acquisition) the same lock, making it “reentrant”
- The thread holding the lock can acquire the lock multiple times without deadlocking itself
import java.util.concurrent.locks.ReentrantLock
val reentrantLock = ReentrantLock()
fun accessSharedResource () {
reentrantLock.lock()
try {
// access shared resource
} finally {
reentrantLock.unlock()
}
}
What is "Reentrant"?
ReadWriteLock
- Allows concurrent access to shared resources for read operations but exclusive access for write operations
- At any point in time, either one thread is writing on the resource (or) one or more threads are reading on it
- Used in scenarios wherein a shared resource is read more often than written
- Implemented using the
ReentrantReadWriteLock
class in Kotlin
import java.util.concurrent.locks.ReentrantReadWriteLock
val readWriteLock = ReentrantReadWriteLock()
fun readSharedResource () {
readWriteLock.readLock.lock()
try {
// read shared resource
} finally {
readWriteLock.readLock.unlock()
}
}
fun writeSharedResource () {
readWriteLock.writeLock.lock()
try {
// write to shared resource
} finally {
readWriteLock.writeLock.unlock()
}
}
Order of requests when using ReadWriteLock?
Fair
mode - acquisition order is same as the order of arrivalNon-fair
(default) mode - order is not guarenteed- Java docs on ReentrantReadWriteLock
Semaphore
- Allows
n
number of threads to access a shared resource concurrently Semaphore
class in Kotlin provides theacquire()
andrelease()
methods
import java.util.concurrent.Semaphore
val semaphore = Semaphore(3)
fun accessSharedResource () {
semaphore.acquire()
try {
// access shared resource
} finally {
semaphore.release()
}
}
Can all multiple threads access the resource under a write operation?