My expectation was that the program would return the output "1000".
However, every time the program performs a different output occurs.
The increment() method of the Counter class has been synchronized. Would only this be necessary to avoid competing readings?
What would be the correct way to make it count the 1000 increments?
package app;
public class Counter {
private Integer value;
public Counter(int initialValue) {
value = initialValue;
}
public synchronized void increment() {
value = value + 1;
}
public int getValue() {
return value;
}
}
package app;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
Counter contador = new Counter(0);
ExecutorService executor = Executors.newFixedThreadPool(10);
for(int i = 0; i < 1000; i++) {
executor.submit(() -> {
contador.increment();
});
}
System.out.println(contador.getValue());
}
}