Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is volatile needed, in case of only synchronized access [duplicate]

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

like image 403
fbenoit Avatar asked Oct 06 '15 15:10

fbenoit


People also ask

Do you need volatile with synchronized?

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..

Do we need volatile in synchronized block?

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 should volatile be used?

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.


1 Answers

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

like image 136
Davide Lorenzo MARINO Avatar answered Oct 09 '22 11:10

Davide Lorenzo MARINO