Question

Java provides AtomicInteger,AtomicLong etc which basically compiles to CAS instructions at hardware level. But why such AtomicXXX classes do not exist for other primitive types like short and floating point numbers like float and double?

Was it helpful?

Solution

You can't CAS on less than a word. AtomicBoolean is implemented using an int and float could be implemented using an int and double using a long.

AFAIK, these were added as part of Doug Lea's concurrency library being included and there hadn't been enough of a need to have Atmoic versions of these types before.

IMHO an AtomicDouble could be useful, but I avoid using float whenever possible due to the lack of precision.

OTHER TIPS

There are too many primitive types:)

If Java support generics for primitive types, we could have Atomic<short> etc. for all primitive types.

Without that, we have to declare AtomicXxx for each Xxx primitive type. API designers may find that unappealing.

The same thing happens in Java8. We have a generic Function<A,B>. But for performance reasons we would like to have primitive versions of Function, so we have IntFunction which is kind of Function<int,B>. But that is only done for int, long, double. There are no ShortFunction etc. They got too many "primitivized" types [1] and they are sick of it, so they stopped at these 3 types.

[1] http://download.java.net/jdk8/docs/api/java/util/function/package-summary.html

See also Brian's answer : http://mail.openjdk.java.net/pipermail/lambda-dev/2013-March/008535.html

It's quite easy to cap an AtomicInteger to a value. Let's say you want that to be a short. You can wrap the AtomicInteger into your custom type and use the modulo operation to cap the value. After reaching the max value, the value is recycled in the same manner when it would have hit the Integer.MAX value in the original AtomicInteger implementation.

public class AtomicShort
{
  private AtomicInteger root = new AtomicInteger();

  public short incrementAndGet()
  {
    return (short) (root.incrementAndGet() % Short.MAX);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top