Created
February 18, 2016 13:04
-
-
Save sorokod/ceec2d0205660ff0a103 to your computer and use it in GitHub Desktop.
A JMH benchmark comparing the throughput of
synchronized vs ReentrantLock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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