No. The +=
operation is not thread-safe. It requires locking and / or a proper chain of "happens-before" relationships for any expression involving assignment to a shared field or array element to be thread-safe.
(With a field declared as volatile
, the "happens-before" relationships exist ... but only on read and write operations. The +=
operation consists of a read and a write. These are individually atomic, but the sequence isn't. And most assignment expressions using =
involve both one or more reads (on the right hand side) and a write. That sequence is not atomic either.)
For the complete story, read JLS 17.4 ... or the relevant chapter of "Java Concurrency in Action" by Brian Goetz et al.
As I know basic operations on primitive types are thread-safe ...
Actually, that is an incorrect premise:
- consider the case of arrays
- consider that expressions are typically composed of a sequence of operations, and that a sequence of atomic operations is not guaranteed to be atomic.
There is an additional issue for the double
type. The JLS (17.7) says this:
"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."
In a comment, you asked:
So what type I should use to avoid global synchronization, which stops all threads inside this loop?
In this case (where you are updating a double[]
), there is no alternative to synchronization with locks or primitive mutexes.
If you had an int[]
or a long[]
, you could replace them with AtomicIntegerArray
or AtomicLongArray
and make use of those classes' lock-free update. However, there is no AtomicDoubleArray
class, or even an AtomicDouble
class.
(UPDATE - someone pointed out that Guava provides an AtomicDoubleArray
class, so that would be an option. A good one actually.)
One way of avoiding a "global lock" and massive contention problems might be to divide the array into notional regions, each with its own lock. That way, one thread only needs to block another thread if they are using the same region of the array. (Single writer / multiple reader locks could help too ... if the vast majority of accesses are reads.)
synchronized
around the loop instead would probably help quite a bit - right now, you're entering and leaving the critical section every iteration of the loop, which is likely going to dominate the runtime entirely for this piece of code. – Batangas