Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A JMH benchmark comparing the throughput of synchronized vs ReentrantLock
package concurrent;
/**
* java -jar target\benchmarks.jar concurrent -t N -wi 10 -i 20 -rf csv -tu ms -si true
*/
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@State(Scope.Benchmark)
public class ReentrantLockVsSynchronized {
@Param({"ReentrantLock", "Synchronized"})
private String lockMode;
@State(Scope.Benchmark)
public static class Counter {
private static long value;
}
@State(Scope.Benchmark)
public static class JvmLock {
private static Object lock = new Object();
}
@State(Scope.Benchmark)
public static class RLock {
private static Lock lock = new ReentrantLock();
}
@Benchmark
public void measure(JvmLock jvmLock, RLock rLock, Counter counter) {
switch (lockMode) {
case "Synchronized":
doSynchronized(jvmLock, counter);
case "ReentrantLock":
doReentrantLock(rLock, counter);
}
}
public void doReentrantLock(RLock rLock, Counter counter) {
rLock.lock.lock();
try {
Counter.value++;
} finally {
rLock.lock.unlock();
}
}
public void doSynchronized(JvmLock jvmLock, Counter counter) {
synchronized (jvmLock.lock) {
Counter.value++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment