Create a gist now

Instantly share code, notes, and snippets.

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;
public class ReentrantLockVsSynchronized {
@Param({"ReentrantLock", "Synchronized"})
private String lockMode;
public static class Counter {
private static long value;
public static class JvmLock {
private static Object lock = new Object();
public static class RLock {
private static Lock lock = new ReentrantLock();
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) {
try {
} finally {
public void doSynchronized(JvmLock jvmLock, Counter counter) {
synchronized (jvmLock.lock) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment