开发者

Using compareAndSet for Thread safety

开发者 https://www.devze.com 2023-01-30 15:52 出处:网络
How is the following demo code thread-safe? We are ensuring whether the value is not modified in CAS instruction and then doing an increment on int. Doesn\'t return v + 1; step beat the whole purpose

How is the following demo code thread-safe? We are ensuring whether the value is not modified in CAS instruction and then doing an increment on int. Doesn't return v + 1; step beat the whole purpose as it can skip updates of threads.

Here atomic integer is used to mimic a non blocking int counter.

//Here value is an atomic integer
public int increment() 
{
   int v;
   for(;;) 
   {
      v = value.get();
      if(value.compareAndSet(v, v + 1))
         return v + 1;   
   }
}

Shouldn't the code be like this:

public int increment() 
{
   int v;
   for(;;) 
   {
      v = value.get();
      if(value.compareAndSet(开发者_开发问答v, v + 1))
         return value.get();   
   }
}


compareAndSet() returns true if the current value equals the expected value v, and thus the value was updated to v + 1.

In your first version, if both threads get the same initial value then one will succeed (updating to v + 1) and the other will fail (since the current value is no longer v) and retry using v + 1 and v + 2.

If this code is intended to return unique keys then the first version is correct, since at the point compareAndSet() returned true the current value is guaranteed to be v + 1 (even if only briefly). The second version may return duplicate values due to a race condition if another thread modifies the value in between your calls to compareAndSet() and get().

That said, you might want to investigate AtomicInteger's incrementAndGet() method, which does pretty much the same thing but more efficiently (no explicit looping).


Define "work".

Let's say value is initially zero. If the first function is called 100 times it would return each number between 1 and 100 exactly once. The second function doesn't have this property.

Both functions can produce values that are out of date by the time the function returns.

Which is more "correct" really depends on the expected semantics of increment.

0

精彩评论

暂无评论...
验证码 换一张
取 消