Atomic Boolean – what & when to use?

Posted: November 10, 2011 in Java
Tags: ,

Lets see what the Java API says about Atomic Boolean

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/atomic/AtomicBoolean.html

A boolean value that may be updated atomically. An AtomicBoolean is used in applications such as atomically updated flags, and cannot be used as a replacement for a Boolean.

Example:

Consider the following scenario where multiple threads need to check and change the boolean.

The belowcode snippet is not thread-safe

if (!initialized) {    
 initialize();    
 initialized = true; 
} 

Hence in such situation, we fix it usingAtomic Boolean

AtomicBoolean initialized= new AtomicBoolean(false); if (initialized.compareAndSet(false, true)) {     
          initialize(); 
} 

Note : public final boolean compareAndSet(boolean expect, boolean update)

Advertisements
Comments
  1. Vinita says:

    The info on this blog is handy.

  2. Wonderful piece of information. Never heard of this Atomic Boolean before, though the blog explained the idea behind the whole thingy, in a simple and easy to understand logic. Great work 🙂

  3. Sushil says:

    what if we just change the position
    if (!initialized) {
    initialized = true;
    initialize();
    }

  4. xyz says:

    May I know what is the meaning of thread safe?

    • houssemzaier says:

      ThreadSafe u can find it in some JSP application like this (safethread=”true” )
      and that mean that program can only be accessed by one thread each Time.

  5. DagnerMouse says:

    So where is the useful information that does something other than repeat examples from the documentation?

    Is AtomicBoolean appropriate to use as a replacement for synchronizing around an Object in order to update a boolean value which indicates whether or not a thread should continue to run, for example? I mean, since that is likely to be the most common use of a boolean…?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s