只需找到一些關於非阻塞算法的信息,所以想要在實踐中使用它們。我將一些代碼從同步更改爲非阻塞,所以我想問一下我是否做得正確並保存了以前的功能。將同步方法轉換爲非阻塞算法
同步代碼:
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();
}
我是否已經正確所做的一切,還是我錯過了一些東西:
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();
}
}
我的非阻塞算法的選擇嗎?對代碼的任何建議和使用非阻塞方法來設置一般的abject?
你不應該使用「this.persistentState.set(newPersistentState)」作爲compareAndSet更新persistentState的值 – hahn
僅當將值設置爲newPersistentState並因此再次將其設置爲newPersistentState後,compareAndSet纔會從while循環中跳出,這不是必需的,正如hahn所述。如果需要,那麼這將是一個檢查後行爲的方式,這是容易出現陳舊的數據問題。謝天謝地,事實並非如此。 – Madhusudhan