Skip to content

Commit

Permalink
Fixed ConcurrentModificationException and lazy not keeping cached value
Browse files Browse the repository at this point in the history
  • Loading branch information
pyricau committed Sep 11, 2024
1 parent 7acf6f3 commit 38ce69d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ class MainThreadMessageScopedLazy<T>(val provider: () -> T) : ReadOnlyProperty<A
thisRef: Any?,
property: KProperty<*>
): T {
valueOrNull?.let {
return it
}
check(MainThreadMessageSpy.enabled) {
"Can't use a MainThreadMessageScopedLazy when MainThreadMessageSpy is not enabled."
}
Expand Down
3 changes: 2 additions & 1 deletion papa-main-trace/src/main/java/papa/MainThreadMessageSpy.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package papa

import android.os.Build.VERSION
import android.os.Looper
import java.util.concurrent.CopyOnWriteArrayList

object MainThreadMessageSpy {

Expand All @@ -12,7 +13,7 @@ object MainThreadMessageSpy {
)
}

private val tracers = mutableListOf<Tracer>()
private val tracers = CopyOnWriteArrayList<Tracer>()

var enabled = false
private set
Expand Down
34 changes: 33 additions & 1 deletion papa/src/androidTest/java/papa/test/MainThreadMessageSpyTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import papa.MainThreadMessageSpy.Tracer
import papa.MainThreadTriggerStack
import papa.internal.mainHandler
import papa.internal.postAtFrontOfQueueAsync
import papa.mainThreadMessageScopedLazy
import papa.test.utilities.SkipTestIf
import papa.test.utilities.TestActivity
import papa.test.utilities.dismissCheckForUpdates
Expand Down Expand Up @@ -78,6 +79,14 @@ class MainThreadMessageSpyTest {
.inOrder()
}

@Test
fun no_ConcurrentModificationException_when_iterating_after_onCurrentMessageFinished_removes_its_tracer() {
runOnMainSync {
MainThreadMessageSpy.onCurrentMessageFinished {}
MainThreadMessageSpy.onCurrentMessageFinished {}
}
}

@Test
fun enabled_by_default() {
val enabled = getOnMainSync {
Expand Down Expand Up @@ -200,4 +209,27 @@ class MainThreadMessageSpyTest {
assertThat(inputCallbackFrameRenderedUptime).isEqualTo(inputTriggerFrameRenderedUptime)
assertThat(isFrameRenderedInChoreographerFrame).isTrue()
}
}

@Test
fun mainThreadMessageScopedLazy_value_is_cached_for_same_message() {
val scopedLazy by mainThreadMessageScopedLazy { Any() }
val (msg1Read1, msg1Read2) = getOnMainSync {
scopedLazy to scopedLazy
}

assertThat(msg1Read1).isSameInstanceAs(msg1Read2)
}

@Test
fun mainThreadMessageScopedLazy_value_is_cleared_between_messages() {
val scopedLazy by mainThreadMessageScopedLazy { Any() }
val msg1Read = getOnMainSync {
scopedLazy
}
val msg2Read = getOnMainSync {
scopedLazy
}

assertThat(msg1Read).isNotSameInstanceAs(msg2Read)
}
}

0 comments on commit 38ce69d

Please sign in to comment.