Reputation: 7347
I couldn't really think of a great title for this question, but the question is would the following call to Atomic.set
in the Foo
constructor be atomic, or could the thread switch before the call to AtomicInteger.set
?
public class Foo {
private final Atomic atomic = new Atomic();
public Foo() {
atomic.set(10);
}
private static class Atomic {
private final AtomicInteger atomicInt = new AtomicInteger();
public void set(int i) {
atomicInt.set(i);
}
}
}
Upvotes: 2
Views: 171
Reputation: 31279
There is no guarantee in the Java Language Specification or Java Virtual Machine Specification that there is no other Thread running between the invocation of the method itself and the invocation of atomic.set()
inside it.
It all depends on the JVM, your hardware, etc. If you have multiple CPU's, the other CPU's won't even know where one CPU is in the code, unless you use Thread synchronization features in Java. (which you are not doing, at least not between the beginning of your method add the invocation of atomic.set
)
The leaves the question "why do you care?" but the above is the answer to the question that you asked.
Upvotes: 4