javamultithreadingcounteratomicinteger

Thread safe counter- Atomic Integer not working


I have (say) 10 threads. All threads increment the counter and the same will be logged. The counter is an atomic integer but sometimes I am getting duplicate values in the counter. What I expect is- counter to be threadsafe, allow counter to be incremented by an only thread at a time, read by an only thread at a time. What should I do differently?! Thank you

Class A{
 public void AM(){
   ExecutorService executor = Executors.newFixedThreadPool(threadPoolCount);
   List tasks = new ArrayList(tasklist);
   for(loop tasks) {
   Future<t> futureObjects = executor.invokeAll(task);
  }
 }
}
Class B implements Callable{
    public Object call(){
      //call method log
  }
}
Class C {
  static AtomicInteger counter = new AtomicInteger(1);
  public void log(){
    log("counter: "+counter)
    counter.getAndIncrement();
  }
}

Solution

  • With given below code, you wont see duplicate values in your log. You are trying to print before updating which could lead to multiple thread printing the same value:

    Class C {
      static AtomicInteger counter = new AtomicInteger(1);
      public void log(){
        int count = counter.getAndIncrement();
        log("counter: "+count)
      }
    }