Skip to content

Commit fe1a609

Browse files
[KTLN-449] Difference Between Lock.withLock and synchronized in Kotlin (#1041)
* aded unit tests * made code changes * code fixes * code fixes * code fixes * code changes * code fixes
1 parent db81fd9 commit fe1a609

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package com.baeldung.withLockVsSynchronize
2+
3+
import kotlinx.coroutines.runBlocking
4+
import kotlinx.coroutines.sync.Mutex
5+
import kotlinx.coroutines.sync.withLock
6+
import org.junit.jupiter.api.Assertions.assertEquals
7+
import org.junit.jupiter.api.Test
8+
import java.util.concurrent.locks.ReentrantLock
9+
import kotlin.concurrent.thread
10+
import kotlin.concurrent.withLock
11+
12+
13+
class WithLockVsSynchronizeUnitTest {
14+
15+
object ObjectToLockOn
16+
val lockObject = ReentrantLock()
17+
@Test
18+
fun `test synchronized keyword usage on a class`() {
19+
val counter = CounterClass()
20+
val threads = List(500) { index ->
21+
thread {
22+
val value = counter.incrementAndGet()
23+
assertEquals(index + 1, value)
24+
}
25+
}.forEach { it.join() }
26+
27+
assertEquals(500, counter.getCount())
28+
}
29+
30+
@Test
31+
fun `test withLock method usage`() {
32+
val counter = LockCounterClass()
33+
val threads = List(500) { index ->
34+
thread {
35+
val value = counter.incrementAndGet()
36+
assertEquals(index + 1, value)
37+
}
38+
}.forEach { it.join() }
39+
40+
assertEquals(500, counter.getCount())
41+
}
42+
43+
fun toSynchronized() = synchronized(ObjectToLockOn) {
44+
println("Synchronized function call")
45+
}
46+
47+
@Synchronized
48+
fun synchronizedMethod() {
49+
println("Synchronized function call")
50+
}
51+
52+
fun performSynchronizedOperation(){
53+
54+
lockObject.withLock {
55+
println("Synchronized function call")
56+
}
57+
}
58+
}
59+
60+
class CounterClass {
61+
private var count = 0
62+
63+
@Synchronized
64+
fun incrementAndGet(): Int {
65+
return ++count
66+
}
67+
68+
@Synchronized
69+
fun getCount(): Int {
70+
return count
71+
}
72+
73+
}
74+
75+
class LockCounterClass {
76+
private var count = 0
77+
private val lock = ReentrantLock()
78+
79+
fun incrementAndGet(): Int {
80+
lock.withLock {
81+
count++
82+
return count
83+
}
84+
}
85+
86+
fun getCount(): Int {
87+
return lock.withLock {
88+
count
89+
}
90+
}
91+
}
92+

0 commit comments

Comments
 (0)