JMU
Atomic Variables
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Motivation (cont.)
Motivation (cont.)
Atomic Variable Classes
An Example Revisited
An Example Revisited (cont.)

The Counter Class

javaexamples/atomic/Counter.java
import java.util.concurrent.atomic.*;

/**
 * An implementation of Runnable that increases a mutable integer.
 *
 * This version uses the AtomicInteger class to show how it corrects
 * the problems of using shared mutable state.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0
 */
public class Counter implements Runnable
{
    private int                iterations;
    private AtomicInteger      mutable;
    
    /**
     * Explicit Value Constructor.
     *
     * @param mutable    The AtomicInteger to use
     * @param iterations The number of times to increment the AtomicInteger
     */
    public Counter(AtomicInteger mutable, int iterations)
    {
        this.mutable    = mutable;        
        this.iterations = iterations;        
    }
    
    /**
     * The code to run in the thread of execution.
     */
    public void run()
    {
        for (int i=0; i<iterations; i++)
        {
            mutable.incrementAndGet();
        }
        System.out.printf("Value: %d\n", mutable.get());
    }
}
        
An Example Revisited (cont.)

The Application

javaexamples/atomic/CounterDriver.java
import java.util.concurrent.atomic.*;

/**
 * An application that illustrates how the AtomicInteger class can prevent
 * some of the problems that can arise
 * when using shared mutable state.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 2.0
 */
public class CounterDriver
{
    private static final int ITERATIONS = 1000000;    
    private static final int THREADS    = 5;    

    /**
     * The entry point of the application.
     *
     * @param args  The command line arguments
     */
    public static void main(String[] args)
    {
        AtomicInteger       mutable;

        mutable = new AtomicInteger(0);
        
        for (int i=0; i<THREADS; i++)
        {
            Thread thread = new Thread(new Counter(mutable, ITERATIONS));
            thread.start();
        }
    }
}
        
Adders
Atomic Arrays
The AtomicReference java.util.concurrent.atomic.AtomicReference Class
What About Atomic Floating Point Numbers?