MathContext.DECIMAL32 vs MathContext.DECIMAL64, which one to use, and why?

2.4k Views Asked by At

Should I use MathContext.DECIMAL32 or MathContext.DECIMAL64? I have looked at the documentation, but I couldn't really understand when to use either.

I'm using BigDecimal to represent a percentage that I want to apply to an amount of money. Something like this:

...
final MathContext mc = MathContext.DECIMAL32;
BigDecimal amount = getAmount(args);
float percent = getPercent().floatValue();
BigDecimal percentAsBd = new BigDecimal(percent/100.f, mc).setScale(4, RoundingMode.HALF_UP);
BigDecimal threshold = amount.multiply(percentAsBd);
...

I'm using oracle java 1.8, ubuntu 14.04, Intel core i7 (64bit)

1

There are 1 best solutions below

5
On

Depending upon your system's architecture, the instruction set for any 64 bit type operation will be split across two CPUs if you aren't on a x64 chipset. With your Intel core i7 (x64) any issues around this are negated.

Updated: 01/09/2016

According to JVM specifications assignment to any 64-bit value assignment requires two 32-bit assignments.

public class IdGenerator {
  private long id;
  public IdGenerator() {
    id = 0;
  }
  public int getNextId() {
    ++value;
  }
}

Based on that assumption the above call to getNextId is not atomic. If this class is used in a multiple thread context, the result getNextId() may not be fully accurate e.g. these calls may produce the following ids 0,1,3,5,6,7,8,10. You would not get this behaviour with a 32-bit type on an x86 platform.

Update 5/9/2016

Hopefully the following link will help with my answer

http://preshing.com/20130618/atomic-vs-non-atomic-operations/