如何使对象(一个可变堆栈)线程安全?

ris*_*p89 2 multithreading scala thread-safety

如何使Scala对象具有线程安全性.

class Stack {
    case class Node(value: Int, var next: Node)

    private var head: Node = null
    private var sz = 0

    def push(newValue: Int) {
        head = Node(newValue, head)
        sz += 1
    }

    def pop() = {
        val oldNode = head
        head = oldNode.next
        oldNode.next = null
        sz -= 1
    }

    def size = sz    //I am accessing sz from two threads
}
Run Code Online (Sandbox Code Playgroud)

这个类显然不是线程安全的.我想让它成为线程安全的.

提前致谢,

生命值

Dan*_*wak 6

只是因为它很有趣,你也可以通过弹出headAtomicReference并synchronized完全避免它来使这个线程安全.正是如此:

final class Stack {
  private val head = new AtomicReference[Node](Nil)

  @tailrec
  def push(newValue: Int) {
    val current = head.get()
    if (!head.compareAndSet(current, Node(newValue, current))) {
      push(newValue)
    }
  }

  @tailrec
  def pop(): Option[Int] = head.get() match {
    case current @ Cons(v, tail) => {
      if (!head.compareAndSet(current, tail))
        pop()
      else
        Some(v)
    }

    case Nil => None
  }

  def size = {
    def loop(node: Node, size: Int): Int = node match {
      case Cons(_, tail) => loop(tail, size + 1)
      case Nil => size
    }

    loop(head.get(), 0)
  }

  private sealed trait Node
  private case class Cons(head: Int, tail: Node) extends Node
  private case object Nil extends Node
}
Run Code Online (Sandbox Code Playgroud)

这避免了完全锁定并提供了比synchronized版本更好的吞吐量.值得注意的是,这种虚假的线程安全数据结构很少是一个好主意.在数据结构级别处理同步和状态管理问题有点像尝试在XML解析器中处理IO异常:您试图在错误的位置解决正确的问题而您没有所需的信息去做.例如,上面的堆栈非常安全,但它在操作中肯定不一致(例如,您可以推送并随后弹出到堆栈中并得到None结果).

你更好的选择是使用一个不变的栈(像List),并抛出该到AtomicReference,如果你需要共享的可变状态.