Ferguzz
Ferguzz

Reputation: 6097

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

Upvotes: 2

Views: 7368

Answers (4)

delly
delly

Reputation: 1

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;  

Upvotes: 0

Binil Thomas
Binil Thomas

Reputation: 13799

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?

Upvotes: 4

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46415

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()

Upvotes: 2

Sebastian Zarnekow
Sebastian Zarnekow

Reputation: 6729

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

Upvotes: 1

Related Questions