Class AutoDrainingCounter

java.lang.Object
org.kiwiproject.beta.concurrent.AutoDrainingCounter
All Implemented Interfaces:
Closeable, AutoCloseable

@Beta public class AutoDrainingCounter extends Object implements Closeable
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 Details

    • AutoDrainingCounter

      public AutoDrainingCounter(Duration drainPeriod)
    • AutoDrainingCounter

      public AutoDrainingCounter(Duration drainPeriod, @Nullable IntConsumer drainCallback)
  • Method Details

    • createAndStart

      public static AutoDrainingCounter createAndStart(Duration drainPeriod)
    • 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 calls stop(). Implementing Closeable lets this class participate in automatic resource management via the try-with-resources mechanism.
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
    • get

      public int get()
    • getAndIncrement

      public int getAndIncrement()
    • incrementAndGet

      public int incrementAndGet()