Skip to content

Commit eba24c5

Browse files
committed
Add thread saftey to exceptions
1 parent 2001616 commit eba24c5

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

core/kotlinx-coroutines-test/src/TestCoroutineExceptionHandler.kt

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ interface ExceptionCaptor {
1616
*
1717
* During [cleanupTestCoroutines] the first element of this list will be rethrown if it is not empty.
1818
*/
19-
val exceptions: MutableList<Throwable>
19+
val exceptions: List<Throwable>
2020

2121
/**
2222
* Call after the test completes.
@@ -30,16 +30,25 @@ interface ExceptionCaptor {
3030
* An exception handler that can be used to capture uncaught exceptions in tests.
3131
*/
3232
class TestCoroutineExceptionHandler: ExceptionCaptor, CoroutineExceptionHandler {
33+
val lock = Object()
34+
3335
override fun handleException(context: CoroutineContext, exception: Throwable) {
34-
exceptions += exception
36+
synchronized(lock) {
37+
_exceptions += exception
38+
}
3539
}
3640

3741
override val key = CoroutineExceptionHandler
3842

39-
override val exceptions = LinkedList<Throwable>()
43+
private val _exceptions = mutableListOf<Throwable>()
44+
45+
override val exceptions
46+
get() = _exceptions.toList()
4047

4148
override fun cleanupTestCoroutines() {
42-
val exception = exceptions.firstOrNull() ?: return
43-
throw exception
49+
synchronized(lock) {
50+
val exception = _exceptions.firstOrNull() ?: return
51+
throw exception
52+
}
4453
}
4554
}

0 commit comments

Comments
 (0)