Reputation: 5108
I have to implement a blocking and synchronized queue in scala.
If I don't miss something, synchronizing is pretty simple, but for my queue to be blocking I could only think of that (which works) :
def pop() : T = {
this.synchronized
{
_read()
if(_out.isEmpty) throw new Empty()
val ret = _out.head
_out = _out.tail
_length -= 1
return ret
}
}
def waitPop() : T =
{
var ret : Option[T] = None
// Possibly wait forever
while(ret.isEmpty)
{
try { ret = Some(pop) }
catch { case e : Empty => Thread.sleep(1000) }
}
ret.get
}
The problem here is Thread.sleep
, it could compromise performance, couldn't it ?
Of course, putting a lower value would mean consuming more of the CPU.
Is there a way to wait properly ?
Thanks.
Upvotes: 2
Views: 1843
Reputation: 5108
Thanks to Voo, I got what I needed :
def waitPop() : T =
{
this.synchronized
{
while(isEmpty) wait
pop
}
}
While in push, I added notifyAll
(still in a synchronized
block).
notify
was also working, but with notifyAll
the result appears less deterministic.
Thanks a lot !
Upvotes: 1