Skip to content

Instantly share code, notes, and snippets.

@Nava2
Last active January 18, 2016 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nava2/37589a8d55219079e501 to your computer and use it in GitHub Desktop.
Save Nava2/37589a8d55219079e501 to your computer and use it in GitHub Desktop.
Adds "RAII"-style locking for Java's "ReadWriteLock"
import java.util.concurrent.locks.ReadWriteLock
/**
* Companion object for "scala-like" concurrent utilities
*/
object Concurrent {
/**
* Adds `this.synchronized` style locking for Java's ReadWriteLock.
* @param rwLock
*/
implicit class RichReadWriteLock[LockT <: ReadWriteLock](val rwLock: LockT) {
/**
* Locks the underlying lock with a "read" lock and performs locking around the function call
* @param f Function that is wrapped between lock/unlock
* @tparam U Optional type that is returned
* @return Instance returned from function, can be Unit
* @see java.util.concurrent.locks.ReadWriteLock#readLock()
*/
def readSafe[U](f: => U): U = {
val lock = rwLock.readLock()
lock.lock()
try {
f
} finally {
lock.unlock()
}
}
/**
* Locks the underlying lock with a "write" lock and performs locking around the function call
* @param f Function that is wrapped between lock/unlock
* @tparam U Optional type that is returned
* @return Instance returned from function, can be Unit
* @see java.util.concurrent.locks.ReadWriteLock#writeLock()
*/
def writeSafe[U](f: => U): U = {
val lock = rwLock.writeLock()
lock.lock()
try {
f
} finally {
lock.unlock()
}
}
}
}
import java.util.concurrent.locks.ReadWriteLock
class Test {
import Concurrent._
private var myValue = 1
private val lock = new ReentrantReadWriteLock()
def readValue() = {
lock.readSafe {
// lock on entry
myValue
// on exit, the lock is freed
}
}
def writeValue(newValue: Int) = {
lock.writeSafe {
// Same thing, but we're writing
myValue = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment