Created
July 18, 2011 23:33
-
-
Save hideaki-t/1090953 to your computer and use it in GitHub Desktop.
check performance and consistency of several counter implementations.
This file contains 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 test { | |
static final int n = 500_000_000; | |
int i = 0; | |
int si = 0; | |
volatile int vi = 0; | |
AtomicInteger ai = new AtomicInteger(0); | |
AtomicInteger ai2 = new AtomicInteger(0); | |
abstract class Incrementable { | |
abstract int inc(); | |
} | |
final Incrementable normal = new Incrementable() { | |
int inc() { return i++; } | |
}; | |
final Incrementable volatileInc = new Incrementable() { | |
int inc() { return vi++; } | |
}; | |
final Incrementable atomicInc = new Incrementable() { | |
int inc() { return ai.getAndIncrement(); } | |
}; | |
final Incrementable synchronizedInc = new Incrementable() { | |
int inc() { synchronized(this) { return si++; } } | |
}; | |
final Incrementable casInc = new Incrementable() { | |
int inc() { | |
int i; | |
do { | |
i = ai2.get(); | |
} while (!ai2.compareAndSet(i, i+1)); | |
return i; | |
} | |
}; | |
public void b(String mode) { | |
final Incrementable inc; | |
switch (mode) { | |
case "volatile": | |
inc = volatileInc; | |
break; | |
case "atomic": | |
inc = atomicInc; | |
break; | |
case "synchronized": | |
inc = synchronizedInc; | |
break; | |
case "normal": | |
inc = normal; | |
break; | |
case "cas": | |
inc = casInc; | |
break; | |
default: | |
throw new RuntimeException(mode); | |
} | |
for (int t = 0; t < 3; t++) { | |
new Thread() { | |
public void run() { | |
yield(); | |
final long start = System.currentTimeMillis(); | |
for (int i = 0; i < n; i++) { | |
inc.inc(); | |
} | |
int l = inc.inc(); | |
System.out.printf("%d, %d\n", l, System.currentTimeMillis() - start); | |
} | |
}.start(); | |
} | |
} | |
public static void main(String[] args) { | |
new test().b(args[0]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment