Atomic Variables
in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
addAndGet()
, decrementAndGet()
,
incrementAndGet()
getAndAdd()
, getAndDecrement()
,
getAndIncrement()
compareAndSet()
, weakCompareAndSet()
get()
, lazySet()
, set()
NonatomicInteger
class
to demonstrate the problems that can arise when
using shared mutable stateSynchronizedInteger
class to
demonstrate how these problems could be overcome with
synchronizationAtomicInteger
instead
Counter
Classimport 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()); } }
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(); } } }
DoubleAdder
(for a variety of reasons)static long Double.doubleToLongBits(double value)
static double Double.longBitsToDouble(long bits)