1
public class SynchroExample {

   public final AtomicInteger integer = new AtomicInteger(0);

   private ExecutorService service = Executors.newFixedThreadPool(100);

   public void syn() {
      for (int i = 0; i < 1000; i++) {
          service.submit(() -> {
              integer.incrementAndGet();
          });
       }
       service.shutdown();
       System.out.println(integer.get());
   }

   public static void main(String [] args) {
      SynchroExample ex = new SynchroExample();
       ex.syn();
    }
}

Can someone please explain why this code doesn't work? I was under the impression that AtomicInteger is threadsafe. And this code is not returning 1000.

Paul Verest
  • 60,022
  • 51
  • 208
  • 332

1 Answers1

3

AtomicInteger is thread safe, but you have called AtomicInteger#get before all tasks finished. ExecutorService#shutdown is not waiting for tasks to finish.

See ExecutorService#shutdown docs:

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

Use

service.awaitTermination(10, TimeUnit.SECONDS)

to wait for all tasks finished.

Bedla
  • 4,789
  • 2
  • 13
  • 27
  • Obviously this example is just for proof of concept, but is there any way to shut down the executor service ONLY once all tasks have finished completing? Instead of hardcoding a 10 second time limit? I also noticed that if I remove the service.shutdown(), this program would still fail (return the wrong number, presumably for the same reason that the tasks have not completed), but the program also hangs forever. Is this because I have hanging threads which have not been terminated? – Harshil Garg Jul 21 '18 at 00:23
  • Sure, there is lot of ways described here: https://stackoverflow.com/questions/3269445/executorservice-how-to-wait-for-all-tasks-to-finish – Bedla Jul 21 '18 at 00:29
  • Yes, it hangs because uninterrupted threads. `shutdown` method does not interrupt running threads, it only instructs `ExecutorService` to not accept next tasks. `shutdownNow` interrupts threads. There is really nice example of two-phase shutdown in `ExecutorService` javadoc. – Bedla Jul 21 '18 at 00:42