Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: What is the different between AtomicBoolean and a static boolean variable when locking a thread?

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.

like image 471
Hexor Avatar asked Aug 20 '12 09:08

Hexor


People also ask

What is the difference between AtomicBoolean and boolean?

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.

What is AtomicBoolean in Java?

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.

What does static boolean mean?

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”.

How does AtomicBoolean compare?

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.


2 Answers

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.

like image 128
Marko Topolnik Avatar answered Oct 04 '22 00:10

Marko Topolnik


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

like image 25
Cratylus Avatar answered Oct 02 '22 00:10

Cratylus