面试题
(1)LongAccumulator与LongAddr类的结构
(2)LongAddr与LongAccumulator类有什么区别?
LongAccumulator类原理分析
/** * Creates a new instance using the given accumulator function * and identity element. * @param accumulatorFunction a side-effect-free function of two arguments * @param identity identity (initial value) for the accumulator function */ public LongAccumulator(LongBinaryOperator accumulatorFunction, long identity) { this.function = accumulatorFunction; base = this.identity = identity; }
@FunctionalInterface public interface LongBinaryOperator { /** * Applies this operator to the given operands. * * @param left the first operand * @param right the second operand * @return the operator result */ //根据两个参数计算并返回一个值 long applyAsLong(long left, long right); }
如何使用LongAccumulator
LongAdder longAdder = new LongAdder(); new LongAccumulator(new LongBinaryOperator() { @Override public long applyAsLong(long left, long right) { return left+right; } },0);
LongAddr的add方法
public void add(long x) { Cell[] as; long b, v; int m; Cell a; if ((as = cells) != null || !casBase(b = base, b + x)) { boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[getProbe() & m]) == null || !(uncontended = a.cas(v = a.value, v + x))) longAccumulate(x, null, uncontended); } }
LongAccumulator的accumulate方法
public void accumulate(long x) { Cell[] as; long b, v, r; int m; Cell a; if ((as = cells) != null || (r = function.applyAsLong(b = base, x)) != b && !casBase(b, r)) { boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[getProbe() & m]) == null || !(uncontended = (r = function.applyAsLong(v = a.value, x)) == v || a.cas(v, r))) longAccumulate(x, function, uncontended); } }
(3)LongAddr与LongAccumulator类相同点?
参考书籍:
Java并发编程之美