I wrote the following program to understand racing:
import java.util.concurrent.*;
class RaceCount
{
static int count = 0;
public static void main(String [] args)
{
ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 1000; i++)
{
executor.submit(new Callable<String>() {
public String call() throws Exception {
count++; return "Incremented";
}
});
}
executor.shutdown();
System.out.println(count);
}
}
Obviously, the count was much less than 1000. So, I changed the call() method signature to:
public synchronized String call() throws Exception {
But, the result was still less than 1000. If I use newFixedThreadExecutor(1000) instead of newSingleThreadExecutor, then I get the expected 1000 even if the call() method is not prefixed with synchronized keyword.
So, my queries are:
1. How to synchronize the threads in the case of newSingleThreadExecutor?
2. Why no synchronization is required, when newFixedThreadExecutor is used?