Shall the emitting
variable be volatile? the emit()
method is called from different threads, and emit must be visible.
But it is accessed in synchronized
blocks only. The // ...
are places where the work is done, but emitting
is not referenced here.
So, if the structure of synchronized
is fix, do I still need a volatile
for emitting
or not? (and why?)
static final class C {
boolean emitting = false; // shall be volatile ?
public void emit() {
synchronized (this) {
if (emitting) {
return;
}
// ...
emitting = true;
}
// ...
synchronized (this) {
if (!condition()) {
emitting = false;
return;
}
}
// ...
}
Frank
You can do synchronization without using synchronized block. It's not a necessary to use volatile variable in it... volatile updates the one variable from main memory..and synchronized Update all shared variables that have been accessed from main memory.. So you can use it according to your requirement..
volatile and Thread Synchronization synchronized methods and blocks provide both of the above properties at the cost of application performance. volatile is quite a useful keyword because it can help ensure the visibility aspect of the data change without providing mutual exclusion.
When To Use Volatile in C/C++ A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change: Memory-mapped peripheral registers.
If it is accessed only from synchronized
blocks is not needed the volatile
keyword.
Synchronized guarantees that changes to variables accessed inside the synchronized block are visible to all threads entering a synchronized block.
From the book Java concurrency in practice:
To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
- Initializing an object reference from a static initializer;
- Storing a reference to it into a volatile field or Atomic Reference ;
- Storing a reference to it into a final field of a properly constructed object;
- Storing a reference to it into a field that is properly guarded by a lock.
Note: guarded by a lock means entered in a synchronized block
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With