今天发现java提供了一个很好的原子类,该原子类可以把传入的参数保证原子性,所以一般在构造单例的时候就可以发挥很大的作用。
在网络请求的时候也有一定的作用,比如一次网络请求开始的时候,
你可以自定义一个变量private static AtomicBoolean mRequestingStart= new AtomicBoolean(false);当网络请求开始的时候你就把这个值设置为true。当这个网络没有执行完成的时候, 你就可以先跳出这次网络请求
在构造单例的时候,
private static final AtomicReference<你的单例类> INSTANCE = new AtomicReference<>();
这样保证单例不被重复创建
取出的时候
private static SingleInstance getInstance() {
for (; ; ) {
SingleInstance manager = INSTANCE.get();
if (manager != null) return manager;
manager = new SingleInstance ();
if (INSTANCE.compareAndSet(null, manager)) return manager;
}