Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap 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 there are multiple threads running, and one of them needs to swap the value of bool and making the new value visible for other threads, do these 2 approaches have the same problem of allowing for another thread's operation to happen in-between the read and write, or does AtomicBoolean assure that nothing will happen in-between the call to .get() and .set()?

like image 789
Tirafesi Avatar asked Jan 03 '23 19:01

Tirafesi


1 Answers

AtomicBoolean cannot assure nothing will happen between the get() and set().
You could create 3 methods get(), set() and swap() that synchronize on the same object.

You could 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
like image 195
Robert Kock Avatar answered Jan 05 '23 08:01

Robert Kock