think in java - concurrency - Atomicity

# what is atomic operation?

atomic operations are not interrupted by the threading mechanism. (context switch)

hence, we can take advantage of this to write lock-free code which does not need to be synchronized.


# atomicity applies to 'simple operations' on primitive types except for longs && doubles, why?

JVM is allowed to perform read and write of 64-bit quantities as 2 separate 32-bit operations (non-amotic),

context switch may happen in the middle of a read or write.


# what's the visibility problem on multiprocessor system?

changes made by one task may be not visible to other tasks because this change is stored temporarily in a local cache, then different tasks will have a different view of the application's state.

BUT, synchronization mechanism, on the other hand, forces changes made by one task to be visible to others.

volatile also ensure visibility, this means as soon as a write occurs for a field, all reads will see the change.

你可能感兴趣的:(think in java - concurrency - Atomicity)