Skip to content

Instantly share code, notes, and snippets.

@devth
Created September 3, 2015 23:21
Show Gist options
  • Save devth/23204d452468234d77b4 to your computer and use it in GitHub Desktop.
Save devth/23204d452468234d77b4 to your computer and use it in GitHub Desktop.
/** 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