What is a race condition in Java, and why is it so hard to reproduce?
A race condition is when the result of your program depends on the order in which the threads happen to run.
There is no error message and no wrong answer in the code itself. The code is correct for one order of execution and wrong for another, and the order is decided by the operating system and by the moment when the processor decides to switch from one thread to another.
So why is it so hard to reproduce? Three reasons.
The first one is that the switch between threads happens at points that the programmer does not control. It usually happens when a thread waits for something or when a time slice runs out, and neither of those is written down in your code.
The second one is that the window between the read and the write is tiny. It is usually a handful of instructions, so the chance of two threads landing in that window at the same time is low.
The third one is that the machine matters. A computer with more processors changes the timing, and so does a computer that is doing other work at the same time. That is why a race that never appears on your machine appears on the server, and why it appears once a week and not every time.
The next question in this topic looks at how to show one and how to fix it.