I'm wondering if a getter method for a private boolean field forces the other threads to get the latest updated value? Is this an alternative for volatile field? For example:
Class A {
private boolean flag;
public boolean getFlag() {
return this.flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
vs
Class B {
public volatile boolean flag;
}
Edit: Is it true that the entire object is cached by a thread (including the private field), so that when I call the getter it will return the cached private field?
No, getter will not cause the field to be synchronized.
when talking about reading and writing a primitive in a multi-threaded environment, we have three problems, caused by the CPU
Getter doesn't solve any of these problem. even if it was, the JIT compiler may completely optimize that function away. than what?
Volatile is one of the ways to solve of the problems above. so does a lock. they ensure that one thread reads the latest value of the primitive, or make sure that a value being written is visible to other threads. they also cause the assembly instructions to run exactly as they were compiled, without any blending.
As a side note, the generated assembly may look completely different from what you have written in your code. you ask yourself "I wrote in my code to read from flag
, so why wouldn't the program read from the field itself?" the compiler may do whatever it sees fit to make the assembly fast as possible. by not adding any locks or volatile specifier, you basically told the compiler that no multi-threaded access is involved and the compiler (and subsequently, the CPU) is free to assume that the object is not touched by multiple threads. it could be that this object may not be created at the first place. the JIT compiler may say "well, declare this boolean in a register and treat that as the entire object". it is very possible.
Edit: Is it true that the entire object is cached by a thread (including the private field), so that when I call the getter it will return the cached private field?
You cannot assume that. it is up to the JVM, the underlying OS and the underlying CPU. it may be cached completely, partially or not at all. to remind you, most of the CPU's out there have more than one cache line, even if the object is cached, where is it cached? in the registers or one of the cache lines?