Java – if multiple threads are updating the same variable, what should be done to update the variable correctly for each thread?
If multiple threads are updating the same variable, what should I do to update the variable correctly for each thread?
Any help would be appreciated
Solution
There are several options:
1) Synchronization is not used at all
This works only if the data is of primitive type (not long / double), and you don't care about reading stale values (which is unlikely)
2) Declare the field volatile
This will ensure that stale values are not read It also applies to objects (assuming that the object will not change after creation) because of the guarantee of volatile variables (see "Java Memory Model")
3) Using Java util. concurrent. Atomiclong, atomicinteger, etc
They are thread safe and support special operations, such as atomic increment and atomic comparison and setting operations
4) Use the same lock to protect read and write
This method provides mutual exclusion, which allows to define a large atomic operation in which multiple data members are manipulated as a single operation