diff options
Diffstat (limited to 'test/pos/MailBox.scala')
-rw-r--r-- | test/pos/MailBox.scala | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/test/pos/MailBox.scala b/test/pos/MailBox.scala new file mode 100644 index 0000000000..c44da9fdfa --- /dev/null +++ b/test/pos/MailBox.scala @@ -0,0 +1,68 @@ +package test; + +import scala.concurrent._; + +class MailBox with Monitor { + private abstract class Receiver { + def isDefined(msg: Any): boolean; + var msg: Any = null; + } + + private val sent = new LinkedList[Any]; + private var lastSent = sent; + private val receivers = new LinkedList[Receiver]; + private var lastReceiver = receivers; + + def send(msg: Any): unit = synchronized { + var r = receivers, r1 = r.next; + while (r1 != null && !r1.elem.isDefined(msg)) { + r = r1; r1 = r1.next; + } + if (r1 != null) { + r.next = r1.next; r1.elem.msg = msg; r1.elem.notify; + } else { + lastSent = lastSent.insert(msg); + } + } + + def receive[a](f: PartialFunction[Any, a]): a = { + val msg: Any = synchronized { + var s = sent, s1 = s.next; + while (s1 != null && !f.isDefinedAt(s1.elem)) { + s = s1; s1 = s1.next + } + if (s1 != null) { + s.next = s1.next; s1.elem + } else { + val r = lastReceiver.insert(new Receiver { + def isDefined(msg: Any) = f.isDefinedAt(msg); + }); + lastReceiver = r; + r.elem.wait(); + r.elem.msg + } + } + f(msg) + } + + def receiveWithin[a](msec: long)(f: PartialFunction[Any, a]): a = { + val msg: Any = synchronized { + var s = sent, s1 = s.next; + while (s1 != null && !f.isDefinedAt(s1.elem)) { + s = s1; s1 = s1.next ; + } + if (s1 != null) { + s.next = s1.next; s1.elem + } else { + val r = lastReceiver.insert(new Receiver { + def isDefined(msg: Any) = f.isDefinedAt(msg); + }); + lastReceiver = r; + r.elem.wait(msec); + if (r.elem.msg == null) r.elem.msg = TIMEOUT; + r.elem.msg + } + } + f(msg) + } +} |