Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created August 21, 2013 13:02
Show Gist options
  • Save bdkosher/6294179 to your computer and use it in GitHub Desktop.
Save bdkosher/6294179 to your computer and use it in GitHub Desktop.
tests double-checked locking approach
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