使用 AtomicBoolean 高效并发处理 “只初始化一次” 的功能要求:
private static AtomicBoolean initialized = new AtomicBoolean(false);
public void init(){
if( initialized.compareAndSet(false, true) )
{
// 这里放置初始化代码....
}
}
上面代码相当于:
public static volatile initialized = false;
public void init(){
if( initialized == false ){
initialized = true;
// 这里初始化代码....
}
}
说明:
AtomicBoolean(boolean initialValue)
//Creates a new AtomicBoolean with the given initial value.
public final boolean compareAndSet (boolean expect, boolean update)
//Atomically sets the value to the given updated value if the current value == the expected value.
//参数
//expect the expected value
//update the new value
参考:
http://api.apkbus.com/reference/java/util/concurrent/atomic/AtomicBoolean.html