capacity: Int) { private val queue = ConcurrentLinkedQueue<T>() private val size = AtomicInteger() fun add(value: T): Boolean { if (size.get() == capacity) { return false } queue.offer(value) size.incrementAndGet() return true } fun poll(): T? { val value = queue.poll() ?: return null size.decrementAndGet() return value } fun size(): Int = size.get() } How we test concurrent algorithms in Kotlin Coroutines
capacity: Int) { private val queue = ConcurrentLinkedQueue<T>() private val size = AtomicInteger() fun add(value: T): Boolean { if (size.get() == capacity) { return false } queue.offer(value) size.incrementAndGet() return true } fun poll(): T? { val value = queue.poll() ?: return null size.decrementAndGet() return value } fun size(): Int = size.get() } Ӓۢ GPT ࢶࢤשਸ Ҋ ࢎਊೡ ࣻ ח ٘ ੌөਃ? How we test concurrent algorithms in Kotlin Coroutines
Invalid execution results = Init part: [addLast(4): void] Parallel part: | pollFirst(): 4 | addFirst(-4): void | | | peekLast(): 4 [-,1] | --- values in "[..]" brackets indicate the number of completed operations in each of the parallel threads seen at the beginning of the current operation --- = The following interleaving leads to the error = Parallel part trace: | pollFirst() | | | pollFirst(): 4 at ConcurrentDequeTest.pollFirst(ConcurrentDequeTest.kt:39) | | | first(): Node@1 at ConcurrentLinkedDeque.pollFirst(ConcurrentLinkedDeque.java:915) | | | item.READ: null at ConcurrentLinkedDeque.pollFirst(ConcurrentLinkedDeque.java:917) | | | next.READ: Node@2 at ConcurrentLinkedDeque.pollFirst(ConcurrentLinkedDeque.java:925) | | | item.READ: 4 at ConcurrentLinkedDeque.pollFirst(ConcurrentLinkedDeque.java:917) | | | prev.READ: null at ConcurrentLinkedDeque.pollFirst(ConcurrentLinkedDeque.java:919) | | | switch | | | | addFirst(-4): void | | | peekLast(): 4 | | | thread is finished | | compareAndSet(Node@2,4,null): true at ConcurrentLinkedDeque.pollFirst(..920) | | | unlink(Node@2) at ConcurrentLinkedDeque.pollFirst(ConcurrentLinkedDeque.java:921) | | | result: 4 | | | thread is finished | | How we test concurrent algorithms in Kotlin Coroutines