E187: Synchronized Call on Boxed Class

This warning is emitted when you call the synchronized method on a boxed primitive value (like Int, Boolean, Double, etc.).

Calling synchronized on a boxed primitive is suspicious because:

  • The boxed object may be a different instance each time due to boxing
  • It's unlikely to provide the synchronization behavior you expect
  • Different boxed values of the same primitive may or may not share the same lock

Longer explanation:

You called the synchronized method on a boxed primitive. This might not be what you intended.


Example

def example(): Unit =
  1.synchronized {
    println("hello")
  }

Error

-- [E187] Potential Issue Warning: example.scala:2:4 ---------------------------
2 |  1.synchronized {
  |  ^^^^^^^^^^^^^^
  |  Suspicious synchronized call on boxed class
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | You called the synchronized method on a boxed primitive. This might not be what
  | you intended.
   -----------------------------------------------------------------------------

Solution

Use a dedicated lock object instead:

object Lock

def example(): Unit =
  Lock.synchronized {
    println("hello")
  }

Or use this if inside a class:

class Counter:
  private var count = 0
  def increment(): Int = this.synchronized {
    count += 1
    count
  }