(转)利用CAS算法实现通用线程安全状态机

此页面是否是列表页或首页?未找到合适正文内容。

(转)利用CAS算法实现通用线程安全状态机

标签:mediumicaexce环境否则交换refoid报错

在多线程环境下,如果某个类是有状态的,那我们在使用前,需要保证所有该类的实例对象状态一致,否则会出现意向不到的bug。下面是通用线程安全状态机的实现方法。

public class ThreadSaveState{
private int x;
private int y;

private enum State {NEW, INITIALIZING, INITIALIZED};

private final AtomicReference<State> init = new AtomicReference<State>(State.NEW);

public ThreadSaveState() {
};

public ThreadSaveState(int x, int y) {
initialize(x, y);
}

private void initialize(int x, int y) {
if (!init.compareAndSet(State.NEW, State.INITIALIZING)) {
throw new IllegalStateException(\”Already initialized\”);
}
this.x = x;
this.y = y;
//… Do anything else the original constructor did
init.set(State.INITIALIZED);
}

//所有公共接口,都要先调用该方法检测对象完整性
private void checkInit() {
if (init.get() != State.INITIALIZED) {
throw new IllegalStateException(\”Uninitialized\”);
}
}

//示例公用接口
public int getX() {
checkInit();
return x;
}

//示例公用接口
public int getY() {
checkInit();
return y;
}
}

这种模式利用compareAndSet方法来操作枚举的原子引用,关于compareAndSet方法,其内部是CAS算法,即:Compare and Swap, 翻译成比较并交换,源码如下:

java.util.concurrent包中借助CAS实现了区别于synchronouse同步锁的一种乐观锁,使用这些类在多核CPU的机器上会有比较好的性能.

结合compareAndSet源码我们看下:

/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}

根据注释,CAS有3个操作数,内存值V,旧的预期值A,要修改的新值B。当且仅当预期值A和内存值V相同时,将内存值V修改为B,返回True,否则返回false。

作者: liuzhihao

为您推荐

返回顶部