@@ -15,6 +15,7 @@ import kotlin.time.Duration
1515class FakeClock (initialTimeMs : Long = 0L ) : Clock {
1616 @Volatile private var time = initialTimeMs
1717 private val timers = mutableMapOf<String , FakeNamedTimer >()
18+ private val waiters = mutableListOf<Waiter >()
1819
1920 override fun currentTimeMillis () = time
2021
@@ -24,10 +25,29 @@ class FakeClock(initialTimeMs: Long = 0L) : Clock {
2425 return t
2526 }
2627
28+ @Suppress(" PLATFORM_CLASS_MAPPED_TO_KOTLIN" )
29+ override fun waitOn (target : Any , timeout : Long ) {
30+ synchronized(waiters) {
31+ waiters.add(Waiter (target as Object , time + timeout))
32+ }
33+ (target as Object ).wait()
34+ }
35+
2736 /* * Advance virtual time by [ms] milliseconds, firing any timers that become due. */
2837 fun advance (ms : Long ) {
2938 time + = ms
3039 timers.values.forEach { it.fireDue(time) }
40+ val due = synchronized(waiters) {
41+ waiters.filter { it.fireAt <= time }.also {
42+ waiters.removeIf { it.fireAt <= time }
43+ }
44+ }
45+ // notifyAll() requires holding the target's monitor.
46+ due.forEach { waiter ->
47+ synchronized(waiter.target) {
48+ waiter.target.notifyAll()
49+ }
50+ }
3151 }
3252
3353 /* * Advance virtual time by [time], firing any timers that become due. */
@@ -60,4 +80,7 @@ class FakeClock(initialTimeMs: Long = 0L) : Clock {
6080 }
6181
6282 class Scheduled (val task : TimerTask , val fireAt : Long )
83+
84+ @Suppress(" PLATFORM_CLASS_MAPPED_TO_KOTLIN" )
85+ class Waiter (val target : Object , val fireAt : Long )
6386}
0 commit comments