-
Kotlin Synchonized와 MultiThreadKotlin/Kotlin 2023. 11. 22. 00:01반응형
Synchonized란?
thread-safe를 위해 Java에서는 synchonized 키워드를 활용하여 data의 안정성과 신뢰성을 보장합니다.
kotlin에서는 어떻게 할 수 있을지 알아보겠습니다.
SynchonizedCounter 구현
class SynchronizedCounter { private var count = 0 fun increaseCount(){ count++ } fun getCurrentCount(): Int{ return count } }
increaseCount를 호출하여 count를 증가시키는 클래스입니다.
MultiThread Test
@Test fun `kotlin Synchronized 테스트해보기`(){ val counter = SynchronizedCounter() val concurrentRequest = 1000 val multipleRepeat = 100 val threadPools = Executors.newFixedThreadPool(concurrentRequest) val latch = CountDownLatch(concurrentRequest * multipleRepeat) repeat(concurrentRequest * multipleRepeat) { threadPools.submit { try { counter.increaseCount() } finally { latch.countDown() } } } latch.await() Assertions.assertEquals(counter.getCurrentCount(), concurrentRequest * multipleRepeat) }
십만 번을 호출해 보는 테스트를 작성하였습니다.
테스트 결과
성공하기도 하지만 때때로 실패하기도 하는 테스트가 만들어졌습니다.
경합 횟수를 더 늘려본다면 확실하게 실패합니다.
kotlin-stdlib의 @Synchronized 활용
class SynchronizedCounter { private var count = 0 @Synchronized fun increaseCount(){ count++ } fun getCurrentCount(): Int{ return count } }
간단하게 @Synchronized 어노테이션만 붙여주면 이제 테스트가 통과합니다.
/** * Marks the JVM method generated from the annotated function as `synchronized`, meaning that the method * will be protected from concurrent execution by multiple threads by the monitor of the instance (or, * for static methods, the class) on which the method is defined. * * Note that for an extension function, the monitor of the facade class, where it gets compiled to a static method, is used. * Therefore, this annotation is recommended to be applied only to member functions and properties. * In other cases, use [synchronized] function and explicitly specify the lock to be used. */ @Target(FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER) @Retention(AnnotationRetention.SOURCE) @MustBeDocumented public actual annotation class Synchronized
JVM 메서드를 동기화하여 여러 스레드의 동시 실행으로부터 보호합니다.
'Kotlin > Kotlin' 카테고리의 다른 글
Kotlin 제네릭에 대해 알아보기 (1) 2024.02.29 kotlin operator fun invoke (0) 2024.02.19 Kotlin과 Java의 컴파일 순서 (0) 2023.11.11 [Kotlin] 상태패턴으로 배송상태를 변경해보자 (0) 2023.08.29 [Kotlin] Result란? (0) 2022.12.04