Skip to content

Instantly share code, notes, and snippets.

@CheatEx
Created November 15, 2013 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CheatEx/b0e1de0771c8f0db6d34 to your computer and use it in GitHub Desktop.
Save CheatEx/b0e1de0771c8f0db6d34 to your computer and use it in GitHub Desktop.
private class CompoundFuture[T](totCnt: Int) extends MyFuture[JavaCollection[T]] {
private val lock = new ReentrantLock()
private val done = lock.newCondition()
private var doneCnt = 0
private var ex: Exception = null
private val res = new ArrayList[T](totCnt)
private val succLsnrs = new mutable.ListBuffer[JavaCollection[T] => Unit]()
private val failLsnrs = new mutable.ListBuffer[Exception => Unit]()
def add(item: T) {
lock.lock()
try {
res.add(item)
doneCnt = doneCnt + 1
if (doneCnt == totCnt) {
done.signalAll()
for (lsnr <- succLsnrs)
lsnr(res)
}
}
finally {
lock.unlock()
}
}
def fail(e: Exception) {
lock.lock()
try {
ex = e
done.signalAll()
for (lsnr <- failLsnrs)
lsnr(ex)
}
finally {
lock.unlock()
}
}
def get: JavaCollection[T] = {
lock.lock()
try {
while (doneCnt != totCnt) {
if (ex != null)
throw ex
done.await()
}
res
}
finally {
lock.unlock()
}
}
def listen(success: (JavaCollection[T]) => Unit, failure: (Exception) => Unit) {
lock.lock()
try {
if (ex != null)
failure(ex)
else if (doneCnt == totCnt)
success(res)
else {
succLsnrs.add(success)
failLsnrs.add(failure)
}
}
finally {
lock.unlock()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment