Package org.kiwiproject.beta.concurrent
Class AutoDrainingCounter
java.lang.Object
org.kiwiproject.beta.concurrent.AutoDrainingCounter
- All Implemented Interfaces:
Closeable,AutoCloseable
Trying out an idea for a self-contained thread-safe counter that drains itself on a recurring basis.
Client code determines the "drain period" after which the count is reset to zero, and can increment as often as it needs to. Clients can get the current count at any time. Clients should ensure the counter is "started" before using it; otherwise it won't drain. No checks are done on this in this first implementation.
Clients can also supply a callback which will be called whenever the counter drains. The counter will pass the count before draining to the callback. If a drain callback is provided, its implementation should return quickly, since the current implementation calls it synchronously. Callback implementations can execute asynchronously if desired.
-
Constructor Summary
ConstructorsConstructorDescriptionAutoDrainingCounter(Duration drainPeriod) AutoDrainingCounter(Duration drainPeriod, @Nullable IntConsumer drainCallback) -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Simply callsstop().static AutoDrainingCountercreateAndStart(Duration drainPeriod) static AutoDrainingCountercreateAndStart(Duration drainPeriod, @Nullable IntConsumer drainCallback) intget()intintbooleanisAlive()voidstart()voidstop()
-
Constructor Details
-
AutoDrainingCounter
-
AutoDrainingCounter
-
-
Method Details
-
createAndStart
-
createAndStart
public static AutoDrainingCounter createAndStart(Duration drainPeriod, @Nullable IntConsumer drainCallback) -
start
public void start() -
isAlive
public boolean isAlive() -
stop
public void stop() -
close
public void close()Simply callsstop(). ImplementingCloseablelets this class participate in automatic resource management via th try-with-resources mechanism.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
get
public int get() -
getAndIncrement
public int getAndIncrement() -
incrementAndGet
public int incrementAndGet()
-