What is the output of the following application?.
package pkg; /*from w ww.ja va 2s . c om*/ import java.util.concurrent.*; public class Main { int stroke = 0; public synchronized void swimming() { stroke++; } public static void main(String... laps) { ExecutorService s = Executors.newFixedThreadPool(10); Main a = new Main(); for(int i=0; i<1000; i++) { s.execute(() -> a.swimming()); } s.shutdown(); System.out.print(a.stroke); } }
D.
The application compiles, so Option B is incorrect.
The stroke variable is thread- safe in the sense that no write is lost since all writes are wrapped in a synchronized method, making Option C incorrect.
Even though the method is thread-safe, the value of stroke is read while the threads may still be executing.
The result is it may output 0, 1000, or anything in-between, making Option D the correct answer.
If the ExecutorService method awaitTermination()
is called before the value of stroke is printed and enough time elapses, then the result would be 1000, and Option A would be the correct answer.