Java's Atomic Integer Slot Counter Class

in #java5 years ago

In Java, we can use AtomicInteger to declare a integer that is thread-safe. We can wrap an array of AtomicInteger into a Thread-safe class. The following is a Java class that allows you to create an array of atomic counters. You can then increase each slot or reset the slot. Meanwhile, you can also get the total counts of all the counters in the array.

public class SlotBaseCounter {
  private int slotSize;
  private AtomicInteger[] slotCounter;

  public SlotBaseCounter(int slotSize) {
    if (slowSize < 1) {
      throw new RuntimeException("slowSize smaller than 1.");
    }
    this.slotSize = slotSize;
    this.slotCounter = new AtomicInteger[slotSize];
    for (int i = 0; i < this.slotSize; i++) {
      slotCounter[i] = new AtomicInteger(0);
    }
  }

  public void increaseSlot(int slot) {
    slotCounter[slot].incrementAndGet();
  }

  public void resetSlot(int slot) {
    slotCounter[slot].set(0);
  }

  public int totalCount() {
    return Arrays.stream(slotCounter).mapToInt(slotCounter -gt; slotCounter.get()).sum();
  }

  @Override
  public String toString() {
    return Arrays.toString(slotCounter);
  }
}

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 59866.06
ETH 1573.69
USDT 1.00
SBD 0.42