Created
April 22, 2014 13:15
-
-
Save gdusbabek/11178750 to your computer and use it in GitHub Desktop.
Compare lock vs synchronized
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
import com.codahale.metrics.JmxReporter; | |
import com.codahale.metrics.MetricRegistry; | |
import com.codahale.metrics.Timer; | |
import java.util.Random; | |
import java.util.concurrent.TimeUnit; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReentrantLock; | |
public class RunAndCompare { | |
public static void main(String args[]) { | |
final MetricRegistry metrics = new MetricRegistry(); | |
final UseLock lock = new UseLock(); | |
final UseSync sync = new UseSync(); | |
final Timer lockTimer = metrics.timer("locks"); | |
final Timer syncTimer = metrics.timer("sync"); | |
final Random random = new Random(System.nanoTime()); | |
final int threads = Integer.parseInt(args[0]); | |
// jmx reporting. | |
JmxReporter.forRegistry(metrics) | |
.convertDurationsTo(TimeUnit.MICROSECONDS) | |
.convertRatesTo(TimeUnit.SECONDS) | |
.build() | |
.start(); | |
final Runnable lockRunnable = new Runnable() { | |
@Override | |
public void run() { | |
Timer.Context ctx = lockTimer.time(); | |
lock.doIt(); | |
ctx.stop(); | |
} | |
}; | |
final Runnable syncRunnable = new Runnable() { | |
@Override | |
public void run() { | |
Timer.Context ctx = syncTimer.time(); | |
sync.doIt(); | |
ctx.stop(); | |
} | |
}; | |
final Runnable loop = new Runnable() { | |
@Override | |
public void run() { | |
while (true) { | |
// do each runnable forever. | |
// don't do the same one first every time though. | |
float odds = random.nextFloat(); | |
if (odds < 0.5f) { | |
lockRunnable.run(); | |
syncRunnable.run(); | |
} else { | |
syncRunnable.run(); | |
lockRunnable.run(); | |
} | |
} | |
} | |
}; | |
for (int i = 0; i < threads; i++) { | |
new Thread(loop).start(); | |
} | |
} | |
private static final Random rand = new Random(System.nanoTime()); | |
private static void doBusyWork() { | |
long x = 0; | |
for (int i = 0; i < 100; i++) { | |
x += Math.abs(rand.nextInt() % 1000); | |
} | |
assert x > 0; | |
} | |
private static class UseLock { | |
private final Lock lock = new ReentrantLock(true); | |
public void doIt() { | |
lock.lock(); | |
try { | |
doBusyWork(); | |
} | |
finally { | |
lock.unlock(); | |
} | |
} | |
} | |
private static class UseSync { | |
public synchronized void doIt() { | |
doBusyWork(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment