Created
August 21, 2013 13:02
-
-
Save bdkosher/6294179 to your computer and use it in GitHub Desktop.
tests double-checked locking approach
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 java.util.concurrent.* | |
class Factory { | |
def rand = new Random() | |
def instance | |
def getInstance() { | |
if (instance == null) { | |
synchronized(this) { | |
if (instance == null) { | |
instance = createInstance() | |
} | |
} | |
} | |
instance | |
} | |
def createInstance() { | |
Thread.sleep(rand.nextInt(1000)) // for simulation purposes | |
new Object() | |
} | |
} | |
def factory = new Factory() | |
def createdInstances = [] as Set | |
int nThreads = 10 | |
int nTasks = 100 | |
ExecutorService executor = Executors.newFixedThreadPool(nThreads); | |
def tasks = [] | |
(0..nTasks).each { | |
tasks << { createdInstances << factory.getInstance() } as Callable<Boolean> | |
} | |
executor.invokeAll(tasks) | |
executor.shutdown() | |
executor.awaitTermination(1, TimeUnit.MINUTES) | |
// this "Set" approach assumes the generated instances are distinct | |
assert createdInstances.size() == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment