Is volatility required for synchronized access only?

Will the emitting variable be changed? The emit() method is called from different threads, and the radiation should be visible.
But it is only available in synchronized blocks. // ... are places where work is done, but emitting is not mentioned here.

So, if the synchronized structure is fixed, do I still need 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; } } // ... } 

Franc

+5
source share
1 answer

If it is accessed only from synchronized , the volatile keyword is not required.

Synchronized guarantees that changes to variables accessed within the synchronized block are visible to all threads included in the synchronized block.

From the Java concurrency book in practice:

To publish an object safely , both the reference to the object and the state of the object must be visible to other threads at the same time. A properly constructed object can be safely published:

  • Initializing an object reference from a static initializer;
  • Saving a link to it in the volatile or Atomic Reference field;
  • Saving a link to it in the final field of a correctly constructed object;
  • Saving a link to it in a field that is properly protected by the lock.

Note: protected by a locking device inserted into the synchronized block

+5
source

Source: https://habr.com/ru/post/1233071/


All Articles