是长线程安全吗?

Dón*_*nal 1 java concurrency thread-safety

这个Java类线程安全吗?

class Counter() {

  private Long counter = 0;

  Long get() { return counter; }

  Long inc() { return ++counter; }
}
Run Code Online (Sandbox Code Playgroud)

如果没有,是否可以在不明确使用锁(或synchronized关键字)的情况下使其成为线程安全的?如果没有,那么我猜以下是实现目标的最简单方法吗?

class Counter() {

  private final AtomicLong counter = new AtomicLong(0);

  Long get() { return counter.get(); }

  Long inc() { return counter.incrementAndGet(); }
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 8

不,第一个例子不是线程安全的,因为++counter它不是原子的.例如,没有什么可以阻止两个线程同时执行++counter并丢失其中一个增量.

第二个示例线程安全的,这意味着不会丢失任何增量.值得注意的是,这两个get()inc()返回一个值,很可能是过时的调用者接收到它的时间.