-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAccumulator.java
56 lines (50 loc) · 1.93 KB
/
Accumulator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package juc;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.stream.IntStream;
public class Accumulator {
/**
* slow
*/
@Test
public void atomic() throws InterruptedException {
AtomicLong accumulator = new AtomicLong();
int threadSize = Runtime.getRuntime().availableProcessors() * 4;
CountDownLatch latch = new CountDownLatch(threadSize);
List<Thread> threadList = IntStream.range(0, threadSize).mapToObj(i -> new Thread(() -> {
for (int j = 0; j < 1_000_000; j++) {
accumulator.incrementAndGet();
}
latch.countDown();
}, "t-" + i)).toList();
long start = System.currentTimeMillis();
threadList.forEach(Thread::start);
latch.await();
System.out.println(System.currentTimeMillis() - start);
Assertions.assertEquals(threadSize * 1_000_000L, accumulator.get());
}
/**
* fast
*/
@Test
public void accumulator() throws InterruptedException {
LongAccumulator accumulator = new LongAccumulator(Long::sum, 0);
int threadSize = Runtime.getRuntime().availableProcessors() * 4;
CountDownLatch latch = new CountDownLatch(threadSize);
List<Thread> threadList = IntStream.range(0, threadSize).mapToObj(i -> new Thread(() -> {
for (int j = 0; j < 1_000_000; j++) {
accumulator.accumulate(1);
}
latch.countDown();
}, "t-" + i)).toList();
long start = System.currentTimeMillis();
threadList.forEach(Thread::start);
latch.await();
System.out.println(System.currentTimeMillis() - start);
Assertions.assertEquals(threadSize * 1_000_000L, accumulator.get());
}
}