How to make Scala object thread-safe.
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
}
This class is clearly not threadsafe. I want to make it threadsafe.
Thanks in Advance,
HP
To my mind, the easiest way to make this meaningfully thread-safe would be as follows:
This implementation would allow you to ensure that
push‘s andpop‘s would be atomic, withpopreturning aSomewrapping the value it removed from the top of the stack orNoneif the stack was already empty.As a note, access to the size is synchronized, but you have no way of guaranteeing that it will be correct at any point after it is returned, since multiple threads are able to access the stack, potentially altering its size. If you really do need to know the size exactly accurately, you would have to go about this differently, synchronizing on the whole stack when you use it.