Created
September 3, 2015 23:21
-
-
Save devth/23204d452468234d77b4 to your computer and use it in GitHub Desktop.
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
/** Implicit class to add idiomatic Scala methods to the | |
* InterProcessReadWriteLock read/write lock */ | |
implicit class RichInterProcessReadWriteLock(lock: InterProcessReadWriteLock) { | |
private def acquireAndRelease[A](mutex: InterProcessMutex, fn: => A): Either[Throwable, A] = | |
Try { | |
// blocking operation | |
mutex.acquire() | |
logger.info(s"Lock obtained: $mutex") | |
Right(fn) | |
}.recover { case e => | |
logger.warn("Exception while trying to acquire mutex on lock", e) | |
Left(e) | |
}.get | |
/** Acquire a read lock and run `fn` if active is true, then release the lock */ | |
def acquireReadLock[A](fn: => A): Either[Throwable, A] = | |
acquireAndRelease(lock.readLock(), fn) | |
/** Acquire a write lock and run `fn` if active is true, then release the lock */ | |
def acquireWriteLock[A](fn: => A): Either[Throwable, A] = | |
acquireAndRelease(lock.writeLock(), fn) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment