Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/test/micro/org/openjdk/bench/java/lang/ThreadOnSpinWaitSharedCounter.java
66646 views
1
/*
2
* Copyright (c) 2021, Red Hat Inc. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
package org.openjdk.bench.java.lang;
24
25
import org.openjdk.jmh.annotations.Benchmark;
26
import org.openjdk.jmh.annotations.BenchmarkMode;
27
import org.openjdk.jmh.annotations.Level;
28
import org.openjdk.jmh.annotations.Mode;
29
import org.openjdk.jmh.annotations.OutputTimeUnit;
30
import org.openjdk.jmh.annotations.Param;
31
import org.openjdk.jmh.annotations.Scope;
32
import org.openjdk.jmh.annotations.Setup;
33
import org.openjdk.jmh.annotations.State;
34
35
import java.util.concurrent.TimeUnit;
36
import java.util.concurrent.atomic.AtomicInteger;
37
38
@BenchmarkMode(Mode.AverageTime)
39
@OutputTimeUnit(TimeUnit.MILLISECONDS)
40
@State(Scope.Benchmark)
41
public class ThreadOnSpinWaitSharedCounter {
42
@Param({"1000000"})
43
public int maxNum;
44
45
@Param({"4"})
46
public int threadCount;
47
48
AtomicInteger theCounter;
49
50
Thread threads[];
51
52
void work() {
53
for (;;) {
54
int prev = theCounter.get();
55
if (prev >= maxNum) {
56
break;
57
}
58
if (theCounter.compareAndExchange(prev, prev + 1) != prev) {
59
Thread.onSpinWait();
60
}
61
}
62
}
63
64
@Setup(Level.Trial)
65
public void foo() {
66
theCounter = new AtomicInteger();
67
}
68
69
@Setup(Level.Invocation)
70
public void setup() {
71
theCounter.set(0);
72
threads = new Thread[threadCount];
73
74
for (int i = 0; i < threads.length; i++) {
75
threads[i] = new Thread(this::work);
76
}
77
}
78
79
@Benchmark
80
public void trial() throws Exception {
81
for (int i = 0; i < threads.length; i++) {
82
threads[i].start();
83
}
84
for (int i = 0; i < threads.length; i++) {
85
threads[i].join();
86
}
87
}
88
}
89
90