Skip to content

Instantly share code, notes, and snippets.

@skuro
Created November 23, 2012 14:00
Show Gist options
  • Select an option

  • Save skuro/4135753 to your computer and use it in GitHub Desktop.

Select an option

Save skuro/4135753 to your computer and use it in GitHub Desktop.
Performance evaluation of a synchronized blog vs double checked locking
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
/**
* @author Carlo Sciolla
*/
public class TestSyncBlock {
interface DoSomething {
void doSomething();
}
abstract class AbstractDoSomething implements DoSomething {
final Object monitor = new Object();
}
class Synchronized extends AbstractDoSomething {
private String foo;
public void doSomething() {
synchronized(monitor) {
if (foo == null) {
initFoo();
}
}
}
private void initFoo() {
foo = "foo";
}
}
class DoubleCheckedLocking extends AbstractDoSomething {
private volatile String foo = null;
public void doSomething() {
if (foo == null) {
synchronized (monitor) {
if (foo == null) {
initFoo();
}
}
}
}
private void initFoo() {
foo = "foo";
}
}
@Test
public void testSynchronized() {
final DoSomething syncDoSomething = new Synchronized();
final DoSomething doubleChecked = new DoubleCheckedLocking();
long startDCL = new Date().getTime();
fireThreads(doubleChecked, 10000000);
long dclDuration = new Date().getTime() - startDCL;
System.out.println("Spurious DCL lasted " + dclDuration);
long startSync = new Date().getTime();
fireThreads(syncDoSomething, 10000000);
long syncDuration = new Date().getTime() - startSync;
System.out.println("Spurious sync lasted " + syncDuration);
startDCL = new Date().getTime();
fireThreads(doubleChecked, 10000000);
dclDuration = new Date().getTime() - startDCL;
startSync = new Date().getTime();
fireThreads(syncDoSomething, 10000000);
syncDuration = new Date().getTime() - startSync;
System.out.println("DCL lasted " + dclDuration);
System.out.println("Sync lasted " + syncDuration);
}
private void fireThreads(final DoSomething doSomething, int size) {
ExecutorService executorService = Executors.newFixedThreadPool(8);
for (int i = 0; i < size; i++) {
Future<?> f = executorService.submit(new Runnable() {
public void run() {
doSomething.doSomething();
}
});
}
try {
executorService.shutdown();
boolean finished = executorService.awaitTermination(30, TimeUnit.SECONDS);
if (!finished) {
System.out.println("NOT DONE!");
}
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment