Skip to content

Shared counter

Randgalt edited this page Nov 13, 2011 · 5 revisions

Description

Manages a shared integer. All clients watching the same path will have the up-to-date value of the shared integer (considering ZK's normal consistency guarantees).

Participating Classes

  • SharedCount
  • SharedCountReader
  • SharedCountListener

Usage

Creating a SharedCounter

public SharedCount(CuratorFramework client,
String path,
int seedValue)
Parameters:
client - the client
path - the shared path - i.e. where the shared count is stored
seedValue - the initial value for the count if/f the path has not yet been created

General Usage

SharedCounts must be started:

count.start();

When you are through with the instance, you should call close:

count.close();

int getCount()
Return the current value of the count
Returns:
count

void addListener(SharedCountListener listener)
Add a listener for changes to the count
Parameters:
listener - the listener

public void setCount(int newCount)
throws Exception
Change the shared count value irrespective of its previous state
Parameters:
newCount - new value

public boolean trySetCount(int newCount)
 
Changes the shared count only if its value has not changed since this client last read it. If the count has changed, the value is not set and this client's view of the value is updated. i.e. if the count is not successful you can get the updated value by calling getCount().
Parameters:
newCount - the new value to attempt
Returns:
true if the change attempt was successful, false if not. If the change was not successful, getCount() will return the updated value
Clone this wiki locally