How to change boolean value in multi-threaded environment?

1.

volatile boolean bool = false;
// ...
bool = !bool;

2.

volatile AtomicBoolean bool= new AtomicBoolean(false);
// ...
bool.set(!bool.get());

If multiple threads are running, and one of them needs to change the value booland make the new value visible to other threads, these two approaches have the same problem as for the other thread operation between reading and writing, or AtomicBooleanmake sure that between the call .get()and .set()? nothing will happen

+4
source share
4 answers

AtomicBooleancannot guarantee that nothing will happen between get()and set().

You can create 3 methods get(), set()and swap(), which are synchronized on the same object.

You can try something like this:

public class SyncBoolean
{
  public SyncBoolean()
  {
    value = false;
  }

  public synchronized boolean get()
  {
    return (value);
  }

  public synchronized void set(boolean newValue)
  {
    value = newValue;
  }

  public synchronized void swap()
  {
    value = !value;
  }

  private boolean value;

} // class SyncBoolean
+4
source

, . :

boolean b;
do {
  b = bool.get();
} while (! bool.compareAndSet(b, !b));
+3

bool = !bool, bool.set(!bool.get()) . , .

synchronized(this) {
    bool.set(!bool.get());
}
+1

, , volatile boolean, AtomicBoolean .

, :

  • "" /
  • while AtomicBoolean.compareAndSet

, , . , .

, , , .

To add my contribution, I noticed that you defined your atomic variable as volatile, and just in case, warn you that if you do not reassign this field and you can do it final, you better do it final. volatileapplies only to the actual value of the field, and if you do not change it (you do not use methods set/compareAndSet AtomicBoolean), and you make sure that other threads will see the initialized value ( finaldoes this), there is no point in using it.

0
source

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


All Articles