Class StripedLock

java.lang.Object
org.kiwiproject.concurrent.StripedLock

public class StripedLock extends Object
StripedLock provides simple lambdas for encapsulating a block of code with a read/write lock.

The number of "stripes" indicates the maximum concurrent processes where the lock "key" is hashed and is used to select a lock. This is useful when you want tasks that operate in the same "context" to block one another without blocking unrelated tasks.

See Also:
Implementation Note:
This StripedLock uses Guava's Striped under the covers. The ReadWriteLocks are re-entrant, and read locks can be held by multiple readers, while write locks are exclusive.
  • Constructor Details

    • StripedLock

      public StripedLock()
      Creates a new StripedLock, using DEFAULT_KEY_WHEN_BLANK as the number of stripes.
    • StripedLock

      public StripedLock(int numStripes)
      Creates a new StripedLock with the given number of stripes.
      Parameters:
      numStripes - number of stripes
      See Also:
      • Striped.readWriteLock(int)
    • StripedLock

      public StripedLock(com.google.common.util.concurrent.Striped<ReadWriteLock> lock)
      Create a new StripedLock using the given ReadWriteLock. This is useful if you have multiple interdependent usages that you want to share across the same set of locks.
      Parameters:
      lock - the striped lock to use
  • Method Details

    • runWithReadLock

      public void runWithReadLock(String lockKey, Runnable task)
      Execute a Runnable task using the provided lock key and associated a READ lock.

      This implementation will block until the read lock is acquired.

      Parameters:
      lockKey - the lock key
      task - the task to run
    • supplyWithReadLock

      public <T> T supplyWithReadLock(String lockKey, Supplier<T> task)
      Execute a Supplier using the provided lock key and associated READ lock.

      This implementation will block until the read lock is acquired.

      Type Parameters:
      T - the type of object being supplied
      Parameters:
      lockKey - the lock key
      task - the task to supply a value
      Returns:
      the supplied value
    • runWithWriteLock

      public void runWithWriteLock(String lockKey, Runnable task)
      Execute a Runnable task using the provided lock key and associated a WRITE lock.

      This implementation will block until the write lock is acquired.

      Parameters:
      lockKey - the lock key
      task - the task to run
    • supplyWithWriteLock

      public <T> T supplyWithWriteLock(String lockKey, Supplier<T> task)
      Execute a Supplier using the provided lock key and associated WRITE lock.

      This implementation will block until the write lock is acquired.

      Type Parameters:
      T - the type of object being supplied
      Parameters:
      lockKey - the lock key
      task - the task to supply a value
      Returns:
      the supplied value