Skip to content

Instantly share code, notes, and snippets.

@sheki
Created September 27, 2011 16:51
Show Gist options
  • Save sheki/1245597 to your computer and use it in GitHub Desktop.
Save sheki/1245597 to your computer and use it in GitHub Desktop.
import java.util.concurrent.atomic.AtomicInteger;
public class CyclicCounter {
private final int maxVal;
private final AtomicInteger ai = new AtomicInteger(0);
public CyclicCounter(int maxVal) {
this.maxVal = maxVal;
}
public int increment() {
int curVal, newVal;
do {
curVal = this.ai.get();
newVal = (curVal + 1) % this.maxVal;
} while (!this.ai.compareAndSet(curVal, newVal));
return newVal;
}
public static void main(String[] args)
{
long total=0;
CyclicCounter counter =new CyclicCounter(100);
for(long i=0;i<1000000;i++)
{
long start=System.nanoTime();
counter.increment();
total+=Math.abs(System.nanoTime()-start);
}
System.out.println(total);
}
}

Time taken to run in NanoSeconds for the above two codes. #With Atomic Integer *63272000 *66007000 *63809000 *63360000 *66363000 #With Synchronized *71556000 *77633000 *75588000 *73978000 *71986000

import java.util.concurrent.atomic.AtomicInteger;
public class CyclicCounter {
private final int max;
private int count;
public CyclicCounter(int max) {
if (max < 1) { throw new IllegalArgumentException(); }
this.max = max;
}
public int getCount() {
return count;
}
public synchronized int increment() {
count = (count + 1) % max;
return count;
}
public static void main(String[] args)
{
long total=0;
CyclicCounter counter =new CyclicCounter(100);
for(long i=0;i<1000000;i++)
{
long start=System.nanoTime();
counter.increment();
total+=Math.abs(System.nanoTime()-start);
}
System.out.println(total);
}
}
@dexterous
Copy link

Is there a particular reason you chose not to use AtomicInteger.incrementAndGet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment