Search code examples
javamultithreadingjava.util.concurrent

Executing a method call with Java atomic variables


Suppose I have a code block like this

if (counter < 100) {
    synchronized (counter)
        if (counter < 100) {
            doSomething();
            counter.incrementAndGet();
        }
    }
}

where counter is an AtomicLong. How would I convert this block to not using the synchronized keyword anymore and still keeps its correctness? Or is it impossible?


Solution

  • It all depends on doSomething which you haven't shown. It may rely on being called from within a synchronized block, and may not even be parallelizable.

    One substitution which I think is likely to be acceptable is

    if (counter.getAndIncrement() < 100) {
        doSomething();
    }
    

    But suppose doSomething always throws an exception. In your code the counter can never be incremented, so the condition will always resolve to true. In the above example, it will be called the first 100 times, and even if they fail they will count as an iteration.

    So in short, in order for us say if correctness is maintained then you need to define very specifically what it means for it to be correct.

    If you don't know what it means for it to be correct then you are better off leaving it as it is.