Java: What is the difference between an AtomicBoolean and a static boolean when blocking a thread?

I am writing a stream class called T.

My goal is to ensure that only one thread object is launched at a time.

So, when the thread object is called, it checks the boolean flag named BUSY.

My question is what is different from

private static AtomicBoolean BUSY = new AtomicBoolean(false); 

and

 private static boolean BUSY = false; 

I thought that if you use “static”, all objects will check only one logical variable BUSY to make sure that only one stream object works.

+4
source share
4 answers

You must at least make the volatile boolean and the AtomicBoolean final variable in order to have a comparable solution. Once you do this, there will be no difference in your use case.

The difference arises if you use the AtomicBoolean getAndSet or compareAndSet methods that combine one read and one write action into an atomic integer, since they are not atomic when they are made against volatile .

+7
source

You can use boolean with proper synchronization (and do volatile ) to achieve what you need.
But with AtomicBoolean you can check the current value atomically without having to write your own code for synchronization

+2
source

As said by others, you must make final / volatile variables accordingly.

From what you are describing, I'm afraid that you have a place where you are doing something like this:

 if (!BUSY){ BUSY = true; } 

Please note that this is violated in the absence of donts synchronization, because two threads can check the flag, considering it false and starting its work.

I suggest exploring existing structures for handling concurrency: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html

Especially Semaphore with a single permission may be what you are looking for.

0
source

A useful feature of AtomicBoolean is the ability to continue one thread if and only if BUSY is false, but does not allow other threads to continue working.

 private static AtomicBoolean BUSY = new AtomicBoolean(false); public void doWork(){ if(BUSY.compareAndSet(false,true)){ //do some work BUSY.set(false); }else{ //some other thread won, return now or retry later? } } 

So, here only one thread will be doWork at any given time. You cannot achieve this with volatile boolean , because you cannot be sure that Thread.currentThread() set a boolean.

0
source

All Articles