4 ms·
> x += 1 is not thread-safe Nit, that's true iff x is a primitive without the volatile modifier. That's not true for a volatile primitive.
by hunterpayne 1y ago
> x += 1 is not thread-safe
Nit, that's true iff x is a primitive without the volatile modifier. That's not true for a volatile primitive.
- deleted 1y ago[deleted]
- wmanley 1y agoEven with volatile it’s a load and then a store no? It may not be undefined behaviour, but I don’t think it will be atomic.
- diek 1y agoYou're correct. If you have: public int someField; public void inc() { someField += 1; } that still compiles down to: GETFIELD [someField] ICONST_1 IADD PUTFIELD [somefield] whether 'someField' is volatile or not. The volatile just affects the load/store semantics of the GETFIELD/PUTFIELD ops. For atomic increment you have to go through something like AtomicInteger that will internally use an Unsafe instance to ensure it emits a platform-specific atomic increment instruction.