Search code examples
javaconcurrencyatomicatomic-long

AtomicLong concurrency output not as expected


I was running the following example, expecting the output to be 1000 always but I get 999 sometimes as well. I believe the output should always be 1000 or am I missing something here?

public class AtomicTest {

    public static void main(String[] args) {

        Counter counter = new Counter();
        int count = 1000;
        ExecutorService executorService = Executors.newFixedThreadPool(count);
        
        for(int i=0;i<count;i++) {
            executorService.submit(() -> {counter.inc();});
        }
        
        executorService.shutdown();
        
        System.out.println(counter.getValue());
        
    }

}

class Counter {
    private AtomicLong counter = new AtomicLong();
    
    public void inc() {
        counter.incrementAndGet();
    }
    
    public void dec() {
        counter.decrementAndGet();
    }
    
    public long getValue() {
        return counter.get();
    }
}

Solution

  • Take a look at the JavaDoc for ExecutorService.shutdown()

    This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

    You are not using awaitTermination. You're not waiting for the tasks to complete.