2013-11-04 37 views
2

的getAndIncrement實施的AtomicInteger的執行以下操作:的getAndIncrement實施的AtomicInteger

public final int getAndIncrement() { 
    for (;;) { 
     int current = get(); // Step 1 , get returns the volatile variable 
     int next = current + 1; 
     if (compareAndSet(current, next)) 
      return current; 
    } } 

是不是aVolatileVariable ++的等效? (我們知道這不是一個正確的用法)。沒有同步,我們如何確保這個完整的操作是原子的?如果在步驟1中讀取變量'current'之後,volatile變量的值發生變化,該怎麼辦?

回答

2

的「祕密武器」就是在此呼籲:

compareAndSet(current, next) 

compareAndSet操作是要失敗的(並返回false)如果原始揮發性值已經後同時改變讀,迫使代碼繼續循環。