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
Created
September 27, 2011 16:51
-
-
Save sheki/1245597 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a particular reason you chose not to use AtomicInteger.incrementAndGet?