Creating Atomic Types
suggest changeFor simple multi-threaded code, using synchronization is acceptable. However, using synchronization does have a liveness impact, and as a codebase becomes more complex, the likelihood goes up that you will end up with Deadlock, Starvation, or Livelock.
In cases of more complex concurrency, using Atomic Variables is often a better alternative, as it allows an individual variable to be accessed in a thread-safe manner without the overhead of using synchronized methods or code blocks.
Creating an AtomicInteger:
AtomicInteger aInt = new AtomicInteger(); // default value 0
AtomicInteger aIntOne = new AtomicInteger(1); // initial value 1
AtomicLong, AtomicBoolean, and AtomicReference have the same shape.
AtomicIntegerArray aIntArray = new AtomicIntegerArray(10); // length 10, elements 0
AtomicIntegerArray copied = new AtomicIntegerArray(new int[] {1, 2, 3}); // copy of the given values
AtomicLongArray and AtomicReferenceArray follow the same pattern.
There is no AtomicFloat or AtomicDouble. Store the bits in an AtomicInteger or AtomicLong with Float.floatToIntBits(float) and Float.intBitsToFloat(int), or Double.doubleToLongBits(double) and Double.longBitsToDouble(long). floatToIntBits and doubleToLongBits canonicalize NaN, so two NaN values can compare equal as bits.
sun.misc.Unsafe can also apply atomic operations to primitive fields, but it is an unsupported internal API. Values are handled as int or long. For more on this see sun.misc.Unsafe.