Java: What is the difference between AtomicBoolean and a static Boolean variable when locking a thread?

advertisements

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.


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.