LongAccumulator
LongAdder類是LongAccumulator的一個特例忘分,它提供給用戶一個自定義規(guī)則的可能——accumulatorFunction.
public LongAccumulator(LongBinaryOperator accumulatorFunction,
long identity) {
this.function = accumulatorFunction;
base = this.identity = identity;
}
- java.util.function.LongBinaryOperator
@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);
}
LongBinaryOperator是一個lambda表達式接口拿愧,(a,b)->c,輸入left和right返回一個long值.
LongAccumulator可以實現(xiàn)初始化自定義敷存,LongAdder默認是0募舟,同時猖败,通過LongBinaryOperator领虹,我們可以實現(xiàn)一些計算過程.
LongAccumulator示例
package com.tea.modules.java8.thread.atomic;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.LongBinaryOperator;
/**
* com.tea.modules.java8.thread.atomic
* LongAccumulator學(xué)習(xí)
*
* @author jaymin
* @since 2022/11/7
*/
public class LongAccumulatorDemo {
public static void main(String[] args) {
// left代表base的值届宠,也就是1;
// right代表的是傳進來的值鸟蜡,也就下面accumulate函數(shù)傳的值
LongAccumulator longAccumulator = new LongAccumulator((left, right) -> left * right, 1);
longAccumulator.accumulate(2);
System.out.println(longAccumulator.get());
LongAdder longAdder = new LongAdder();
longAdder.add(1);
System.out.println(longAdder.longValue());
LongAccumulator longAdd = new LongAccumulator(Long::sum, 0);
longAdd.accumulate(1);
System.out.println(longAdd.get());
}
}
這里展示了2個示例膜赃,一個是聲明一個累乘計算器,一個是用LongAccumulator實現(xiàn)了一個LongAdder.
源碼對比
- java.util.concurrent.atomic.LongAccumulator#accumulate
public void accumulate(long x) {
Cell[] as; long b, v, r; int m; Cell a;
if ((as = cells) != null ||
// casBase采用的是lambda表達式返回的值
(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);
}
}
- java.util.concurrent.atomic.LongAdder#add
public void add(long x) {
Cell[] as; long b, v; int m; Cell a;
// casBase采用的是 b+x
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);
}
}