将同步方法转换为非阻塞算法

时间:2016-04-18 15:11:33

标签: java multithreading synchronization nonblocking atomicreference

只需找到有关非阻塞算法的一些信息,因此希望在实践中使用它们。我将一些代码从同步更改为非阻塞,所以我想问一下我是否做得对,并保存了以前的功能。

同步代码:

protected PersistentState persistentState;
protected ClassConstructor(final ID id)
{
    super(id);
    this.persistentState = PersistentState.UNKNOWN;
}
public final synchronized PersistentState getPersistentState()
{
    return this.persistentState;
}

protected synchronized void setPersistentState(final PersistentState newPersistentState)
{
    if (this.persistentState != newPersistentState)
    {
        this.persistentState = newPersistentState;
        notifyPersistentStateChanged();
    }
}

我在非阻塞算法中的替代方案:

     protected AtomicReference<PersistentState> persistentState;
  protected ClassConstructor(final ID id)
    {
        super(id);
        this.persistentState = new AtomicReference<PersistentState>(PersistentState.UNKNOWN);
    }
   public final PersistentState getPersistentState()
    {
        return this.persistentState.get();
    }

    protected void setPersistentState(final PersistentState newPersistentState)
    {
        PersistentState tmpPersistentState;
        do
        {
            tmpPersistentState = this.persistentState.get();
        }
        while (!this.persistentState.compareAndSet(tmpPersistentState, newPersistentState));
        // this.persistentState.set(newPersistentState); removed as not necessary 
        notifyPersistentStateChanged();
    }

我是否已正确完成所有事情,或者我错过了什么?对代码的任何建议和使用非阻塞方法来设置abject一般吗?

1 个答案:

答案 0 :(得分:3)

取决于thread-safe的含义。如果两个线程同时尝试写入,您希望发生什么?是否应该随机选择其中一个作为正确的新值?

这就是最简单的。

protected AtomicReference<PersistentState> persistentState = new AtomicReference<PersistentState>(PersistentState.UNKNOWN);

public final PersistentState getPersistentState() {
    return this.persistentState.get();
}

protected void setPersistentState(final PersistentState newPersistentState) {
    persistentState.set(newPersistentState);
    notifyPersistentStateChanged();
}

private void notifyPersistentStateChanged() {
}

即使状态未发生变化,在所有情况下仍会调用notifyPersistentStateChanged。您需要决定在该场景中应该发生什么(一个线程使A - > B,另一个线程B - > - > A。

但是,如果您只需要调用notify,如果成功转换了该值,您可以尝试以下内容:

 protected void setPersistentState(final PersistentState newPersistentState) {
    boolean changed = false;
    for (PersistentState oldState = getPersistentState();
            // Keep going if different
            changed = !oldState.equals(newPersistentState)
            // Transition old -> new successful?
            && !persistentState.compareAndSet(oldState, newPersistentState);
            // What is it now!
            oldState = getPersistentState()) {
        // Didn't transition - go around again.
    }
    if (changed) {
        // Notify the change.
        notifyPersistentStateChanged();
    }
}