I write a thread class called T.
My purpose is to make sure only one thread object running at a time.
So when the thread object is called, it would check a boolean flag called BUSY.
My question is what is the different between
private static AtomicBoolean BUSY = new AtomicBoolean(false);
and
private static boolean BUSY = false;
I thought if using the 'static', all object would only check one BUSY boolean variable so that would make sure only one thread object is running.
AtomicBoolean has methods that perform their compound operations atomically and without having to use a synchronized block. On the other hand, volatile boolean can only perform compound operations if done so within a synchronized block.
AtomicBoolean class provides operations on underlying boolean value that can be read and written atomically, and also contains advanced atomic operations. AtomicBoolean supports atomic operations on underlying boolean variable. It have get and set methods that work like reads and writes on volatile variables.
static Boolean valueOf(String s) : This method returns a Boolean with a value represented by the specified string 's'. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string “true”.
The method compareAndSet() allows you to compare the current value of the AtomicBoolean to an expected value, and if current value is equal to the expected value, a new value can be set on the AtomicBoolean . The compareAndSet() method is atomic, so only a single thread can execute it at the same time.
You must at least make the boolean variable volatile
and the AtomicBoolean variable final
in order to have a comparable solution. After you do that, there will be no difference for your use case.
The difference comes about if you use AtomicBoolean
's getAndSet
or compareAndSet
methods, which combine one read and one write action into an atomic whole, wheraas these are not atomic when done against a volatile
.
You can use a boolean
and with proper synchronization (and making volatile
) can achieve what you need.
But by using the AtomicBoolean
you can check the current value atomically without the need to write code for synchronization yourself
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