-1

could someone explain me about this code please?

public class Counter {
        private AtomicInteger value = new AtomicInteger();

        public int incrementLongVersion(){//THIS PART2!!!
                int oldValue = value.get();
                while (!value.compareAndSet(oldValue, oldValue+1)){
                         oldValue = value.get();
                }
                return oldValue+1;
        }

}

i mean why can't i just change this code

!value.compareAndSet(oldValue, oldValue+1)

to

false

? I know there will be compile error statement never reached but why

!value.compareAndSet(oldValue, oldValue+1)

is not getting error? isn't it always false too right?

Or why can't I just clear that while loop and just return "oldValue+1"?

Thanks and regards.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Asker
  • 109
  • 7

2 Answers2

1

If incrementLongVersion is called from multiple threads, value.compareAndSet(oldValue, oldValue+1) may return false. The purpose of the while loop is to make sure that the function returns a value that's unique among all working threads.

A better way to implement this would be to simply use incrementAndGet from AtomicInteger.

public class Counter {
        private AtomicInteger value = new AtomicInteger();

        public int incrementLongVersion(){
                return value.incrementAndGet();
        }

}
pablochan
  • 5,625
  • 27
  • 42
-1

It is always false because you know what that function do, however the compiler does not analyze the body of given method call to check the return value will always be the same, false in this case.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99