【问题标题】:Java thread safe counter does not work as expectedJava 线程安全计数器未按预期工作
【发布时间】:2020-11-19 17:34:24
【问题描述】:

我使用 AtomicInteger 实现了以下 Counter 类。我从this文章中复制粘贴了这个类:

public class Counter {
  private final AtomicInteger counter = new AtomicInteger(0);

  public int get() {
      return counter.get();
  }

  public void increment() {
      while (true) {
          int existingValue = get();
          int newValue = existingValue + 1;
          if (counter.compareAndSet(existingValue, newValue)) {
              return;
          }
      }
  }
}

我编写了以下测试以确保它确实是一个线程安全的计数器:

@Test
public void counterWorksAsExpected() {
    IntStream.range(0, 100).forEach(j -> {
        int threads = 100;
        Counter counter = new Counter();

        ExecutorService executorService = Executors.newCachedThreadPool();
        IntStream.range(0, threads).forEach(i -> {
            executorService.execute(counter::increment);
        });
        executorService.shutdown();
        assertEquals(threads, counter.get());
    });
}

但是在某个迭代中,assertEquals 失败了。

我想知道我的Counter 类是否不是线程安全的。

【问题讨论】:

标签: java concurrency atomic


【解决方案1】:

您关闭了执行程序,但您没有在断言之前等待提交的任务完成。在检查结果之前添加对awaitTermination() 的调用。

【讨论】:

    猜你喜欢
    • 2018-04-27
    • 2019-07-30
    • 2020-10-30
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多