IMHO volatile/AtomicInteger . - . , , volatile .
Java 6 update 23.
Average time to synchronized++ 10000000 times. was 110368 us
Average time to synchronized on the class ++ 10000000 times. was 37140 us
Average time to volatile++ 10000000 times. was 19660 us
, .
:
static final Object o = new Object();
static int num = 0;
static final AtomicInteger num2 = new AtomicInteger();
public static void main(String... args) throws InterruptedException {
final int runs = 10 * 1000 * 1000;
perfTest(new Runnable() {
public void run() {
for (int i = 0; i < runs; i++)
synchronized (o) {
num++;
}
}
public String toString() {
return "synchronized++ " + runs + " times.";
}
}, 4);
perfTest(new Runnable() {
public void run() {
for (int i = 0; i < runs; i++)
synchronized (Main.class) {
num++;
}
}
public String toString() {
return "synchronized on the class ++ " + runs + " times.";
}
}, 4);
perfTest(new Runnable() {
public void run() {
for (int i = 0; i < runs; i++)
num2.incrementAndGet();
}
public String toString() {
return "volatile++ " + runs + " times.";
}
}, 4);
}
public static void perfTest(Runnable r, int times) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(times);
long start = System.nanoTime();
for (int i = 0; i < times; i++)
es.submit(r);
es.shutdown();
es.awaitTermination(1, TimeUnit.MINUTES);
long time = System.nanoTime() - start;
System.out.println("Average time to " + r + " was " + time / times / 10000 + " us");
}