-
-
Save CheatEx/b0e1de0771c8f0db6d34 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 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