8000 Fix concurrency bug in Replay by jacksoncheek · Pull Request #43 · UrbanCompass/Snail-Kotlin · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
This repository was archived by the owner on Jul 2, 2021. It is now read-only.

Fix concurrency bug in Replay #43

Merged
merged 4 commits into from
Oct 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions snail-kotlin/src/main/java/com/compass/snail/Replay.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,29 @@ package com.compass.snail

import com.compass.snail.disposer.Disposable
import kotlinx.coroutines.CoroutineDispatcher
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

open class Replay<T>(private val threshold: Int) : Observable<T>() {
private var values: MutableList<T> = mutableListOf()
private val lock = ReentrantLock()

override fun subscribe(dispatcher: CoroutineDispatcher?, next: ((T) -> Unit)?, error: ((Throwable) -> Unit)?, done: (() -> Unit)?): Disposable {
replay(dispatcher, createHandler(next, error, done))
return super.subscribe(dispatcher, next, error, done)
}

override fun next(value: T) {
values.add(value)
values = values.takeLast(threshold).toMutableList()
lock.withLock {
values.add(value)
values = values.takeLast(threshold).toMutableList()
}
super.next(value)
}

private fun replay(dispatcher: CoroutineDispatcher?, handler: (Event<T>) -> Unit) {
values.forEach { notify(Subscriber(dispatcher, handler, this), Event(next = Next(it))) }
lock.withLock {
values.forEach { notify(Subscriber(dispatcher, handler, this), Event(next = Next(it))) }
}
}
}
37 changes: 37 additions & 0 deletions snail-kotlin/src/test/java/com/compass/snail/ReplayTests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ package com.compass.snail
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

class ReplayTests {
private var subject: Replay<String>? = null
Expand Down Expand Up @@ -38,4 +41,38 @@ class ReplayTests {
assertEquals("2", b[0])
assertEquals(2, b.size)
}

@Test
fun testMultiThreadedBehavior() {
val subject = Replay<Int>(1)
var a = 0
var b = 0

subject.subscribe(next = {
a = it
})
subject.subscribe(next = {
b = it
})

val latch = CountDownLatch(2)
thread {
for (i in 1..100) {
subject.next(i)
}
latch.countDown()
}
thread {
for (i in 1..100) {
subject.next(i)
}
latch.countDown()
}
latch.await(1000, TimeUnit.SECONDS)

subject.removeSubscribers()

assertEquals(100, a)
assertEquals(100, b)
}
}
0