The test consistently passes for 10'000 runs. But why is no race condition causing the test to fail ?
The definition of a race condition is that you might get timing problems -- it is not guaranteed. If you ran this on another architecture you might get wildly different results.
However, I don't think that asserts in other threads are seen by junit. For example, if I change you test the following. I do see times that the value differs but the fail
is not seen by the test method -- the test still passes.
if (currentAVal+1 != accessCounter) {
System.out.println("Access counter not equal: "+accessCounter);
Assert.fail();
}
One reason why you may be seeing proper values in accessCounter
is that System.out.println(...)
is a synchronized method which is (as a byproduct) synchronizing the value of accessCounter
.
Also, you are not shutting down your executor nor are you waiting for the executor service to actually complete. You should do something like:
// we shut it down once we've submitted all jobs to it
executor.shutdown();
// now we wait for all of those jobs to finish
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
But this doesn't solve the other thread issue. To actually see the results of the threads you could do something like:
List<Future<?>> futures = new ArrayList<Future<?>>();
for (int executorCount = 0; executorCount < 10000; ++executorCount) {
futures.add(executor.submit(r));
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
for (Future<?> future : futures) {
// this will throw an exception if an assert happened
future.get();
}