How to use synchronized in Scala?

前端 未结 1 415
梦谈多话
梦谈多话 2020-12-29 20:48

I have the following code:

object Foo {
 private var ctr = 0L

 def bar = {
   ctr = ctr + 1
   // do something with ctr
 }
}

The requireme

相关标签:
1条回答
  • 2020-12-29 21:54

    If you don't want an AtomicInteger, here is how to use synchronized

    object Foo {
     private var ctr = 0L
     def getCtr = this.synchronized {
       ctr = ctr + 1
       ctr
     }
     def bar = {
        val currCtr = getCtr
        // do something with currCtr
      }
    }
    

    You need to synchronize on some object. In this case on your current object which is this.

    In short: Scala's format is (and the block can return a value)

    this.synchronized {
       ctr = ctr + 1
       ctr
    }
    

    It is equivalent of java's

    synchronized(this) {
       return ++ctr;   
    }
    

    Scala does not have synchronized methods as java, just blocks.

    Edit

    To answer the question from comment below: synchronized can be used as a method from class AnyRef:

    https://www.scala-lang.org/api/current/scala/AnyRef.html

    final def synchronized[T0](arg0: ⇒ T0): T0
    

    so you are calling a method of your object, just like you would do toString and this.toString.

    0 讨论(0)
提交回复
热议问题