Skip to content

Instantly share code, notes, and snippets.

@CheatEx
Created November 15, 2013 15:54
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/bb4f9005ad756812007b to your computer and use it in GitHub Desktop.
Save CheatEx/bb4f9005ad756812007b 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 res: Either[util.ArrayList[T], Exception] = Left(new util.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 match {
case Left(list) if list.size < totCnt => {
list.add(item)
if (list.size == totCnt) {
done.signalAll()
for (lsnr <- succLsnrs)
lsnr(list)
}
}
case _ => return
}
}
finally {
lock.unlock()
}
}
def fail(e: Exception) {
lock.lock()
try {
res match {
case Left(list) if list.size < totCnt => {
res = Right(ex)
done.signalAll()
for (lsnr <- failLsnrs)
lsnr(ex)
}
case _ => return // Do nothing - either already failed or done.
}
}
finally {
lock.unlock()
}
}
def get: JavaCollection[T] = {
lock.lock()
try {
while (res.left.toOption.exists(_.size < totCnt))
done.await()
res match {
case Left(list) => list
case Right(ex) => throw ex
}
}
finally {
lock.unlock()
}
}
def listen(success: (JavaCollection[T]) => Unit, failure: (Exception) => Unit) {
lock.lock()
try {
res match {
case Left(list) if list.size == totCnt => success(list)
case Left(_) => {
succLsnrs += success
failLsnrs += failure
}
case Right(ex) => failure(ex)
}
}
finally {
lock.unlock()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment