This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Just learning about multithreading with Java. I created a small program that uses multiple threads to count up to a number and then stop. I assumed that, because using something like an int variable (say, int count = 0;) and ++ (as in count++) doesn't define an atomic action, I'd have to put all non-atomic actions in synchronized methods or blocks, and declare non-atomic variables as volatile, which I did.
Everything worked. The program counted to whatever I set it to count and stopped. No interleaving or memory consistency errors (not too clear on the difference between those two things yet).
Then, when I took away the volatile and synchronized keywords and ran the program. It worked just the same no matter what the upper count limit was or how many threads were running. I was expecting to get wrong output.
The following is the altered code, with no synchronization. Just wondering if anyone could point to where my thinking is wrong. Thanks.
Just because there is a race condition -- doesn't mean that you will get an incorrect answer. Thread race conditions means that stuff can go wrong -- it doesn't mean that it will go wrong, nor will you notice it.
Regardless, here are some suggestions...
* Don't have your threads track the total. For example, have 10 threads increment 1,000,000 times may or may not get to 10,000,000. However, having 10 threads increment until they get to 10,000,000 will definitely get to 10,000,000.
* Have more threads -- and if possible, run it on a multicore/multiprocessor machine
* Have more iterations -- with short runs, the racers may start and finish before the others start.
* Remove non-race condition code -- don't pause or print any output until the very end.
All in all, I think that suggestion one is likely your main culprit.