TIL: Tearing
I saw this tweet the other day that mentioned "struct tearing." I'd never heard of struct tearing, so I looked it up.
I wasn't able to find much about struct tearing specifically, but I did find information about tearing in the JVM.
Some processors do not provide the ability to write to a single byte. It would be illegal to implement byte array updates on such a processor by simply reading an entire word, updating the appropriate byte, and then writing the entire word back to memory. This problem is sometimes known as word tearing, and on processors that cannot easily update a single byte in isolation some other approach will be required.
Which makes a lot of sense. The docs then go on to talk about tearing that isn't architecture-specific:
For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64-bit value from one write, and the second 32 bits from another write.
Writes and reads of volatile long and double values are always atomic.
Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values.
The implication here being that it would be possible for a thread to read a
half-updated long
or double
value, which would be nonsense.