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