Java
Concurrency traps
synchronized, volatile, and the race that only appears on the marker's machine.
Concurrency bugs are not hard because threads are hard. They are hard because the bug is invisible until it is not, and then only on a machine that is not yours.
Your laptop has fewer cores, a different scheduler and a warm cache. It will run the broken code correctly ten thousand times. The marker's machine will not.
Three problems wearing one name
"Thread safety" gets used for three separate things, and mixing them up is where most confusion starts.
Atomicity. count++ is three operations: read, add, write. Two threads can
interleave and lose an update. Nothing about int prevents this.
Visibility. A thread can write a value and another thread can simply not see it, indefinitely. Not because the write was slow, but because there is no guarantee it was ever published. Each core has its own view.
Ordering. The compiler and the processor are both allowed to reorder your instructions, as long as a single thread cannot tell. Another thread can tell.
volatile fixes visibility and ordering. It does not fix atomicity, which
is why volatile int count still loses increments. That single sentence is
worth more than any diagram of the memory model.
synchronized, and what it actually gives you
A synchronized block does two things, and everyone remembers only the first.
It gives mutual exclusion: one thread in the block at a time.
It also establishes happens-before: everything the previous holder wrote is guaranteed visible to the next one. That is the half people forget, and it is why removing a lock "because it is only reading" is such a reliable way to make a program mysterious.
Two rules keep you out of the worst of it. Lock on a private final object, not
on this and never on a String or a boxed , because those are shared
in ways you did not intend. And hold the lock for the shortest useful stretch,
but not so short that you have split one operation into two.
More on this is coming, and asking moves it up the list.
Want this written up?
Sign in and tell us. We write the ones people actually ask for, and asking takes one click.
Sign in to askOr sit with someone on it instead of waiting for us to write it.