-
-
Save CheatEx/bb4f9005ad756812007b to your computer and use it in GitHub Desktop.
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
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