JMH模擬鎖高爭用,長臨界區,測試鎖效能

peterzh6發表於2024-04-01

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

}
`

相關文章