Sup!
I am practicing & trying to cope with concurrency Now, I am attempting to count numbers from 1 to N (1000 in my example) using ExecutorService, but unluckily I am not able to receive the expectative result. Here I go:
class Exec {
AtomicInteger sum = new AtomicInteger(0);
public static void main(String[] args) {
for (int i = 0; i < 30; i++) {
Exec exec = new Exec();
exec.run(exec);
}
}
public void run(Exec exec) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
IntStream.range(0, 1000).parallel().forEach(x -> executorService.submit(exec::synchCalc));
executorService.shutdown();
System.out.println(sum.get());
}
public synchronized void synchCalc() {
sum.incrementAndGet();
}
}
The output is:
940
980
976
973
1000
1000
960
968
969
996
969
969
1000
938
997
0
1000
999
1000
734
999
969
1000
238
969
999
969
971
465
999
I've tried several ways of solving my problem: volatile instead of AtomicInteger, synchronizing almost every method, but it doesn't make sense as well. The result is just the same - I never get all 1000 and I don't really realise why so.
I would appreciate any answer in due trouble. Thank you for any help!