Say that I have a private variable and I have a setVariable()
method for it which is synchronized
, isn't it exactly the same as using volatile
modifier?
No. Volatile means the variable isn't cached in any per-thread cache, and its value is always retrieved from main memory when needed. Synchronization means that those per-thread caches will be kept in sync at certain points. In theory, using a volatile variable can come with a great speed penalty if many threads need to read the value of the variable, but it is changed only rarely.
No, calling a synchronized
getXXX/setXXX method is not the same as reading/writing to a volatile
variable.
Multiple threads can concurrently read from or write to a volatile
variable. But only one thread at a time can read from or write to a variable that is guarded by a synchronized
block.
volatile
variables are not synchronized (at least, not in the way synchronized
stuff is synchronized). What volatile
does is ensure that a variable is retrieved each time it's used (ie: it prevents certain kinds of optimization), and IIRC that it's read and written in the correct order. This could conceivably emulate some kinds of synchronization, but it can't work the same if your setter has to set more than one thing. (If you set two volatile
variables, for example, there will be a point where one is set and the other isn't.)
Actually No.
volatile
is actually weaker form of synchronization, when field is declared as a volatile
the compiler and runtime understands that this variable
is shared and operations on it shouldn't be reordered with other memory operations. Volatile variable aren't cached in registers or in caches where they are hidden from other processors, so a read of a volatile
variable always return a recent write by any thread.
just an example :
First thread run :
while(stopped){
... do something
}
Second thread run :
stopped = true;
it's useful to declare stopped as a volatile boolean for the first thread to have a fresh value of it.
There is no any relation.
Basically
- Volatile => it always retrieves parameter's latest value
- Synchronized => it serves only 1 thread at the same time
© 2022 - 2024 — McMap. All rights reserved.