E187: Synchronized Call on Boxed Class — 박스된 클래스에 대한 synchronized 호출

E187: Synchronized Call on Boxed Class — 박스된 클래스에 대한 synchronized 호출

박스된 원시 타입 값(Int, Boolean, Double 등)에 대해 synchronized 메서드를 호출할 때 발생하는 경고예요.

출처: Scala 3 Reference

본문

박스된 원시 타입에 대해 synchronized를 호출하는 것은 이상해요. 그 이유는:

좀 더 자세한 설명 (Longer explanation)

박스된 원시 타입에 대해 synchronized 메서드를 호출했어요. 아마 의도한 바가 아닐 거예요.

예시 (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)

전용 lock 객체를 사용하세요:

object Lock

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

클래스 안이라면 this를 사용하세요:

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

더 알아보기

동기화는 전용 락 객체나 this에 대해 하는 게 안전해요. 박스된 원시 타입의 synchronized는 의미가 없어요.