Java’s Atomic Integer Slot Counter Class


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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);
  }
}
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);
  }
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
208 words
Last Post: Teaching Kids Programming - Brick Layout (Unlimited Knapsack) via Top Down Dynamic Programming Algorithm
Next Post: Teaching Kids Programming - Brick Layout (Unlimited Knapsack) via Bottom Up Dynamic Programming Algorithm

The Permanent URL is: Java’s Atomic Integer Slot Counter Class

Leave a Reply