JMH模拟锁高争用,长临界区,测试锁性能
`package org.example;
import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
@State(Scope.Group)
public class LocksBenchmark {
private ReentrantLock reentrantLock;
private PutMessageSpinLock spinLock;
private int numThreads = 10; // 并发线程数,可根据需要调整
@Setup
public void setup() {
reentrantLock = new ReentrantLock();
spinLock = new PutMessageSpinLock();
}
@Benchmark
@Group("reentrantLock")
@GroupThreads(10) // 根据实际情况调整线程数
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void testReentrantLock() {
reentrantLock.lock();
try {
// 执行计算密集型任务而非sleep
performTask();
} finally {
reentrantLock.unlock();
}
}
@Benchmark
@Group("spinLock")
@GroupThreads(10) // 根据实际情况调整线程数
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void testSpinLock() {
spinLock.acquire();
try {
// 执行计算密集型任务而非sleep
performTask();
} finally {
spinLock.release();
}
}
private void performTask() {
// 模拟的计算密集型任务,替代Thread.sleep
int result = 0;
for (int i = 0; i < 1000000; i++) {
result += i;
}
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}
`