19

既然AtomicInteger可以至少比int受保护的要慢一个数量级synchronized,我为什么要使用 AtomicInteger?

例如,如果我只想以int线程安全的方式增加一个值,为什么不总是使用:

synchronized(threadsafeint) {
  threadsafeint++;
}

而不是使用慢得多的AtomicInteger.incrementAndGet()

4

2 回答 2

19

由于 AtomicInteger 至少比受同步保护的 int 慢一个数量级,我为什么要使用 AtomicInteger?

AtomicInteger 更快。

static final Object LOCK1 = new Object();
static final Object LOCK2 = new Object();
static int i1 = 0;
static int i2 = 0;
static final AtomicInteger ai1 = new AtomicInteger();
static final AtomicInteger ai2 = new AtomicInteger();

public static void main(String... args) throws IOException {
    for(int i=0;i<5;i++) {
        testSyncInt();
        testAtomicInt();
    }
}

private static void testSyncInt() {
    long start = System.nanoTime();
    int runs = 10000000;
    for(int i=0;i< runs;i+=2) {
        synchronized (LOCK1) {
            i1++;
        }
        synchronized (LOCK2) {
            i2++;
        }
    }
    long time = System.nanoTime() - start;
    System.out.printf("sync + incr: Each increment took an average of %.1f ns%n", (double) time/runs);
}

private static void testAtomicInt() {
    long start = System.nanoTime();
    int runs = 10000000;
    for(int i=0;i< runs;i+=2) {
        ai1.incrementAndGet();
        ai2.incrementAndGet();
    }
    long time = System.nanoTime() - start;
    System.out.printf("incrementAndGet: Each increment took an average of %.1f ns%n", (double) time/runs);
}

印刷

sync + incr: Each increment took an average of 32.4 ns
incrementAndGet: Each increment took an average of 20.6 ns
sync + incr: Each increment took an average of 31.4 ns
incrementAndGet: Each increment took an average of 12.9 ns
sync + incr: Each increment took an average of 29.6 ns
incrementAndGet: Each increment took an average of 12.9 ns
sync + incr: Each increment took an average of 35.1 ns
incrementAndGet: Each increment took an average of 16.6 ns
sync + incr: Each increment took an average of 29.9 ns
incrementAndGet: Each increment took an average of 13.0 ns

正如@assylias 建议的那样添加一些争论。它表明,当您真正使用一个线程时,CPU 可以优化访问。

static final Object LOCK1 = new Object();
static final Object LOCK2 = new Object();
static int i1 = 0;
static int i2 = 0;
static final AtomicInteger ai1 = new AtomicInteger();
static final AtomicInteger ai2 = new AtomicInteger();

public static void main(String... args) throws  ExecutionException, InterruptedException {
    for(int i=0;i<5;i++) {
        testSyncInt();
        testAtomicInt();
    }
}

private static void testSyncInt() throws ExecutionException, InterruptedException {
    long start = System.nanoTime();
    final int runs = 1000000;
    ExecutorService es = Executors.newFixedThreadPool(2);
    List<Future<Void>> futures = new ArrayList<>();
    for(int t=0;t<8;t++) {
        futures.add(es.submit(new Callable<Void>() {
            public Void call() throws Exception {
                for (int i = 0; i < runs; i += 2) {
                    synchronized (LOCK1) {
                        i1++;
                    }
                    synchronized (LOCK2) {
                        i2++;
                    }
                }
                return null;
            }
        }));
    }
    for (Future<Void> future : futures) {
        future.get();
    }
    es.shutdown();
    long time = System.nanoTime() - start;
    System.out.printf("sync + incr: Each increment took an average of %.1f ns%n", (double) time/runs/2);
}

private static void testAtomicInt() throws ExecutionException, InterruptedException {
    long start = System.nanoTime();
    final int runs = 1000000;
    ExecutorService es = Executors.newFixedThreadPool(2);
    List<Future<Void>> futures = new ArrayList<>();
    for(int t=0;t<8;t++) {
        futures.add(es.submit(new Callable<Void>() {
            public Void call() throws Exception {
                for (int i = 0; i < runs; i += 2) {
                    ai1.incrementAndGet();
                    ai2.incrementAndGet();
                }
                return null;
            }
        }));
    }
    for (Future<Void> future : futures) {
        future.get();
    }
    es.shutdown();
    long time = System.nanoTime() - start;
    System.out.printf("incrementAndGet: Each increment took an average of %.1f ns%n", (double) time/runs/2);
}

印刷

sync + incr: Each increment took an average of 478.6 ns
incrementAndGet: Each increment took an average of 191.5 ns
sync + incr: Each increment took an average of 437.5 ns
incrementAndGet: Each increment took an average of 169.8 ns
sync + incr: Each increment took an average of 408.1 ns
incrementAndGet: Each increment took an average of 180.8 ns
sync + incr: Each increment took an average of 511.5 ns
incrementAndGet: Each increment took an average of 313.4 ns
sync + incr: Each increment took an average of 441.6 ns
incrementAndGet: Each increment took an average of 219.7 ns
于 2012-07-26T13:46:32.803 回答
2

如果您真的想了解更多关于为什么java.util.concurrent东西更好以及与经典同步方法相比有什么区别的详细信息,请阅读此链接(以及整个博客)

于 2012-07-26T13:50:06.907 回答