Last active
January 18, 2016 19:19
-
-
Save Nava2/37589a8d55219079e501 to your computer and use it in GitHub Desktop.
Adds "RAII"-style locking for Java's "ReadWriteLock"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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