Search code examples
javamultithreadingjvmatomicnative-code

Do Java Atomics only require atomicity with respect to the VM


I was looking at the Java source code for the AtomicInteger class (found here) to see which atomic primitives are required to implement a JVM. I noticed they use the undocumented Unsafe API to implement their atomic integer operations and that the only two primitives they use seem to be the compare and swap and compare and set operations. And the Unsafe class implements these instructions as native methods which leads me to believe they are using the native instructions which perform these primitive operations in the general case. However, not every processor(though most modern ones do) has an instruction set which supports these primitives natively. Now even without native processor support those primitives could be implemented by the VM in a way that guarantees atomicity with other VM threads, but not necessarily with other native threads. So does java require these primitives on the native architecture to have a valid JVM and thus all JVM implementations would support atomicity with native threads, or is the atomicity in java only guaranteed between java threads?


Solution

  • The JNI does not provide any way for a native thread to get the address of a Java variable. All access to the variable, whether from Java bytecode or from a native thread, must go through JVM machinery. So your question really is moot.

    Java atomics "require atomicity with respect to the JVM", and "with respect to the JVM" is the only case that matters.