"are java variables themselves thread safe? when updating variables? " Code Answer

5

it depends on the type of the variable.

doubles and longs (the two 64-bit types in java) are allowed to word-tear if they're not volatile, while all other types (including references) may never tear. word tearing would give you the behavior you're worried about: some of the bytes are from the old value, some of them are from the new value, and the overall result is a value that's neither the old nor new.

this is specified in jls 17.7:

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.

of course, introducing data races introduces a whole host of issues; but your question was specifically targeted at word tearing, so i'm only addressing that here, except to note that "just because you can, doesn't mean you should." you should be careful to analyze each data race you have and prove that it's benign (as some of them are -- like string.hashcode's caching of its values).

By Jim Grant on May 2 2022

Answers related to “are java variables themselves thread safe? when updating variables? ”

Only authorized users can answer the Search term. Please sign in first, or register a free account.