|
| 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