Search code examples
javamultithreadingprimitive

simultaneous update of primitives in Java


I'm solving a problem of iterative calculation of some lower bound of the answer in a multi-threading environment.

During the calculation, it could happen that number of threads would try to update a common primitive variable. It doesn't matters for me which one of them would succeed to write it's value and which would fail.

The only problem I'm bothered about is if it possible that one of the threads would write part of the primitive (e.g. first bytes) and another would write another part (e.g. last bytes) and as a result the value of that primitive would be non of what the threads were trying to write.

A link to an official literature would be very appreciated.

Thanks in advance.


Solution

  • The only problem I'm bothered about is if it possible that one of the threads would write part of the primitive (e.g. first bytes) and another would write another part (e.g. last bytes) and as a result the value of that primitive would be non of what the threads were trying to write.

    Citing the Java Language Specification:

    If a double or long variable is not declared volatile, then for the purposes of load, store, read, and write actions they are treated as if they were two variables of 32 bits each: wherever the rules require one of these actions, two such actions are performed, one for each 32-bit half. The manner in which the 64 bits of a double or long variable are encoded into two 32-bit quantities is implementation-dependent. The load, store, read, and write actions on volatile variables are atomic, even if the type of the variable is double or long.

    Writing to other primitives is always atomic. However, if they are not declared volatile then updates may not be visible to other threads for an arbitrarily long time.