下面的代码是分别是非线程安全的counter和线程安全的counter的实现。
@NotThreadSafe
public class UnsafeCounting implements Servlet {
private long count = 0;
public long getCount() { return count; }
public void service(ServletRequest req, ServletResponse resp) {;
++count;;
}
}
@ThreadSafe
public class Counting implements Servlet {
private final AtomicLong count = new AtomicLong(0);
public long getCount() { return count.get(); }
public void service(ServletRequest req, ServletResponse resp) {
count.incrementAndGet();
}
}
我的问题是如果使用java.lang.Long来保存count,并且是volatile的,这样的counter是否是线程安全的?
public class MyCounting implements Servlet {
private volatile Long count = 0l;
public long getCount() { return count.long; }
public void service(ServletRequest req, ServletResponse resp) {
count = count+1;
}
}