在Scala 2.9.2队列上运行时,我收到罕见的NoSuchElementException错误。我不明白这个例外,因为Queue中有元素。我已经尝试切换到SynchronizedQueue,认为这是一个并发问题(我的队列是从不同的线程编写和读取的),但这并没有解决它。
简化代码如下所示:
val window = new scala.collection.mutable.Queue[Packet]
...
(thread 1)
window += packet
...
(thread 2)
window.dequeueAll(someFunction)
println(window.size)
window.foreach(println(_))
结果是
32
java.util.NoSuchElementException
at scala.collection.mutable.LinkedListLike$class.head(LinkedListLike.scala:76)
at scala.collection.mutable.LinkedList.head(LinkedList.scala:78)
at scala.collection.mutable.MutableList.head(MutableList.scala:53)
at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:59)
at scala.collection.mutable.MutableList.foreach(MutableList.scala:30)
LinkedListLike.head()的文档说
Exceptions thrown
`NoSuchElementException`
if the linked list is empty.
但如果Queue不为空,如何抛出此异常?
答案 0 :(得分:0)
您应该只从一个线程访问window
(可变数据结构)。其他线程应该向该消息发送消息。
Akka允许相对容易的并发编程。
class MySource(windowHolderRef:ActorRef) {
def receive = {
case MyEvent(packet:Packet) =>
windowHolderRef ! packet
}
}
case object CheckMessages
class WindowHolder {
private val window = new scala.collection.mutable.Queue[Packet]
def receive = {
case packet:Packet =>
window += packet
case CheckMessages =>
window.dequeueAll(someFunction)
println(window.size)
window.foreach(println(_))
}
}
要定期查看邮件,您可以schedule定期发送邮件。
// context.schedule(1 second, 1 second, CheckMessages)