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.
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
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Important Update of Delegation Service!
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- 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