E187: Synchronized Call on Value Class
This warning is emitted when you call the synchronized method on a boxed primitive value (like Int, Boolean, Double, etc.) or a value class (like LocalDate).
Calling synchronized on such a class 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
- Starting in JDK 28, it is no longer allowed
Longer explanation:
You called the synchronized method on a value class. 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 value class
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| You called the synchronized method on a value class. This might not be what
| you intended.
-----------------------------------------------------------------------------
Solution
Use a dedicated lock object instead:
object Lock
def example(): Unit =
Lock.synchronized {
println("hello")
}
Or synchronize on this if inside a class:
class Counter:
private var count = 0
def increment(): Int = this.synchronized {
count += 1
count
}
In this article