Skip to content

Shared Semaphore

Randgalt edited this page Aug 11, 2011 · 10 revisions

Description

A counting semaphore that works across JVMs. Uses Zookeeper to hold the lock. All processes in all JVMs that use the same lock path will achieve an inter-process limited set of leases. Further, this mutex is "fair" - each user will get a lease in the order requested (from ZK's point of view).

IMPORTANT: The number of leases in the semaphore is merely a convention maintained by the users of a given path. i.e. no internal checks are done to prevent Process A acting as if there are 10 leases and Process B acting as if there are 20. Therefore, make sure that all instances in all processes use the same numberOfLeases value.

Participating Classes

  • InterProcessSemaphore

Usage

Creating an InterProcessSemaphore

public InterProcessSemaphore(CuratorFramework client,
String path,
int numberOfLeases)
Parameters:
client - client
path - the path to lock
numberOfLeases - the number of leases allowed by this semaphore

General Usage

To acquire one lease/usage, use one of the acquire methods:

public void acquire()

Acquire a lease if one is available. Otherwise block until one is. Each call to acquire must be balanced by a call to release()

public boolean acquire(long time,
TimeUnit unit)

Acquire a lease if one is available - blocks until one is available or the given time expires. Each call to acquire that returns true must be balanced by a call to release() Parameters: time - time to wait unit - time unit Returns: true if a lease was acquired, false if not

To release the acquired lease, call:

public void release()

Release the lease held by this instance

Clone this wiki locally