Each individual call is synchronized, but a compound action such as iteration is not. Hold the lock yourself, or use a concurrent collection instead.
List<Integer> shared = Collections.synchronizedList(new ArrayList<>());
var pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 200; i++) { int v = i; pool.submit(() -> shared.add(v)); }
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("size = " + shared.size());
synchronized (shared) { // required for safe iteration
System.out.println("sum = " + shared.stream().mapToInt(Integer::intValue).sum());
}
size = 200
sum = 19900
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30