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
- Atomicity : it may require the store or load operation more than one assembly instruction, for example, writin into a 64-bit integer on a 32-bit CPU. the current thread may be put to sleep by the operating system in the middle of the instruction sequence.
- Visibility : a thread that runs on one core may not read the latest value that other thread from other core has written. simply because the CPU says so.
- Reordering : in order to make the program run faster, the CPU blends the order of the assembly instructions as it sees fit.
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?
volatile
were the same as a getter then why would we need an entirely new language keyword for it? – Sink