[英]BigDecimal - MathContext.DECIMAL64 vs MathContext.DECIMAL128
[英]MathContext.DECIMAL32 vs MathContext.DECIMAL64, which one to use, and why?
我应该使用MathContext.DECIMAL32
还是MathContext.DECIMAL64
吗? 我看过文档 ,但是我真的不明白何时使用它们。
我正在使用BigDecimal表示要应用于一定金额的百分比。 像这样:
...
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);
...
我正在使用Oracle Java 1.8,Ubuntu 14.04,Intel Core i7(64bit)
根据您系统的体系结构,如果不使用x64芯片组,则任何64位类型操作的指令集都将分配给两个CPU。 使用您的Intel Core i7(x64),可以解决与此相关的所有问题。
更新时间:2016年1月9日
根据JVM规范,对任何64位值的分配都需要两个32位分配。
public class IdGenerator {
private long id;
public IdGenerator() {
id = 0;
}
public int getNextId() {
++value;
}
}
基于该假设,上述对getNextId的调用不是原子的。 如果在多线程上下文中使用此类,则结果getNextId()可能不完全准确,例如,这些调用可能会产生以下ID 0、1、3、5、6、7、8、10。 在x86平台上使用32位类型将不会出现此行为。
更新5/9/2016
希望以下链接对我的回答有所帮助
http://preshing.com/20130618/atomic-vs-non-atomic-operations/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.