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()?
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
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