并行/线程安全的Scala Queue实现?

时间:2016-04-19 18:59:08

标签: scala thread-safety queue

我在scala中有一个链接队列的实现,但它目前不是并行安全的。我不确定我需要做些什么改变才能使这个实现并行安全...任何建议?

class LinkedQueue[A] extends Queue[A] {
  private class Node (var data:A, var next:Node)
  private var head:Node = null
  private var last:Node = null

  def isEmpty():Boolean = head == null

  def peek():A = {
    assert(head != null)
    head.data
  }

  def dequeue():A = {
    assert(head != null)
    val ret = head.data
    head = head.next
    if(head == null) last = head
    ret
  }

  def enqueue(elem:A) {
    if(last == null) {
      head = new Node(elem, null)
        last = head
    } else {
      last.next = new Node(elem, null)
      last = last.next
    }
  }
}

0 个答案:

没有答案