须臾之余

# 面试题

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);
}```

```LongAdder longAdder = new LongAdder();
new LongAccumulator(new LongBinaryOperator() {
@Override
public long applyAsLong(long left, long right) {
return left+right;
}
},0);```

```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);
}
}```

LongAccumulator使用 r = function.applyAsLong(b = base, x)来计算

LongAddr使用casBase(b = base, b + x)来计算

```final void longAccumulate(long x, LongBinaryOperator fn,
boolean wasUncontended) {
....
else if (casBase(v = base, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break;                          // Fall back on using base
}
}```

## 参考书籍：

Java并发编程之美

### 须臾之余

JDK8中新增原子性操作类LongAccumulator

2017/08/24
0
0

Java8在atomic包新增了5个类，分别是，，，，。其中，Sriped64作为父类，其他分别是long和double的具体实现。 下面首先从父类这个类开始讲，其几个类都是遵从它的结构进行实现的。 What is ...

anLA_
2017/11/30
0
0
4、并发增强

4.1 概述 这部分用的不多，仅简单记录一下新特性 4.2 原子值 4.2.1 更新方法 Java 8 增加了两个新方法 updateAndGet 和 accumulateAndGet 用于更新原子类的值，取代老API的循环方式。 4.2.2 ...

2016/06/22
85
0
UITableView 子类--XFSettings

yizzuide
2015/08/22
841
0
KVO探究（二）---原理篇

2017/12/08
0
0

Spring boot 静态资源访问

0. 两个配置 spring.mvc.static-path-patternspring.resources.static-locations 1. application中需要先行的两个配置项 1.1 spring.mvc.static-path-pattern 这个配置项是告诉springboo......

moon888

3
0
hash slot（虚拟桶）

4
0
Kafka 原理和实战

vivo互联网技术

19
0
java数据类型

audience_1

9
0

Java技术剑

27
0