I have the following code:
object Foo {
private var ctr = 0L
def bar = {
ctr = ctr + 1
// do something with ctr
}
}
The requirement is that a ctr
value should be used only once. In my case the same value of ctr
is getting reused. My theory is that this happens because Foo.bar
is called concurrently in different threads (this is the only conclusion I could draw). I have the following modified code as a fix.
object Foo {
private var ctr = 0L
def getCtr = synchronized{
ctr = ctr + 1
ctr
}
def bar = {
val currCtr = getCtr
// do something with currCtr
}
}
I could not find a good guide for using the synchronized
method in Scala. Can anyone let me know if the above code will fix my problem.
EDIT: Based on the comments below, I think AtomicLong
is the best solution for me:
import java.util.concurrent.atomic.AtomicLong
private val ctr = new AtomicLong
def getCtr = ctr.incrementAndGet