开发者

compareAndSet vs incrementAndGet

Doing a course on concurrent programming.

As an example we have

final class Counter {

        private AtomicInteger value;

        public long getValue() {
            return value.get();
        }

        public long increment() {
            int v;
            do {
                v = value.get(开发者_运维问答);
            }
            while(!value.compareAndSet(v, v+1));
            return v+1;
        }
}

Why would you use compareAndSet in this case and not incrementAndGet ?

Thanks


Here the the implementation of AtomicInteger.incrementAndGet() method from the JDK version I have on my machine:

/**
 * Atomically increments by one the current value.
 *
 * @return the updated value
 */
public final int incrementAndGet() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return next;
    }
}

As you can see, the implementation is very similar to yours.

PS: Why do you compute v+1 twice?


From the Java docs,

compareAndSet :

Atomically sets the value to the given updated value if the current value == the expected value.

public final boolean compareAndSet(V expect,
                                   V update)

incrementAndGet :

Atomically increments by one the current value.

public final int incrementAndGet()


Since compareAndSet basically does the same, I can't think about a single reason to use this handwritten implementation of increment.


In your case, the Class Counter implements the value increment in it's own way, and JDK AtomicInteger.incrementAndGet() also implements it in it's own way. But they also use the CAS method compareAndSet(V expect ,V newValue).
So these two kinds of implementation have no difference. The minor difference between the two ways is the circulation form. BTW, answer for compute v+1 twice.

while(!value.compareAndSet(v, v+1));----v+1 is the parameter for function , and realize value to add 1;
        return v+1;  v+1 is the return value;  
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜