Reputation: 196
Simply put, i'm trying to see the difference when using sychronized keyword over just running a function over threads without locks at all.
In this code:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class mainClass {
static int count=0;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable r =new Runnable() {
public synchronized void run() {
count = count + 1;
}
};
IntStream.range(0, 10000)
.forEach(i -> executor.submit(r::run));
executor.shutdown();
System.out.println(count); // 10000
}
}
It doesn't work as i predicated it to work, it returns 10000 in like 40% of the runs. Why is that? Where is the problem? I thought that the function run is being run by only 1 Thread at a time, so there shouldn't be problem, but clearly i'm wrong.
Upvotes: 0
Views: 63
Reputation: 11818
ExecutorService#shutdown
does not wait for tasks to complete. You should use awaitTermination
for that.
See the documentation for ExecutorService#shutdown.
IntStream.range(0, 10000)
.forEach(i -> executor.submit(r::run));
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTE); // <!-- HERE
Upvotes: 4