Skip to content

Commit ed7d0c2

Browse files
committed
Restore context correctly
1 parent f6c7db6 commit ed7d0c2

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

log4j-api-kotlin/src/main/kotlin/org/apache/logging/log4j/kotlin/CoroutineThreadContext.kt

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ class CoroutineThreadContext(
8989
}
9090

9191
private fun setCurrent(contextData: ThreadContextData) {
92-
contextData.map?.let { ContextMap += it } ?: ContextMap.clear()
93-
contextData.stack?.let { ContextStack.set(it) } ?: ContextStack.clear()
92+
ContextMap.clear()
93+
ContextStack.clear()
94+
contextData.map?.let { ContextMap += it }
95+
contextData.stack?.let { ContextStack.set(it) }
9496
}
9597
}

log4j-api-kotlin/src/test/kotlin/org.apache.logging.log4j.kotlin/ThreadContextTest.kt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ class ThreadContextTest {
3838
ContextStack.clear()
3939
}
4040

41+
@DelicateCoroutinesApi
4142
@Test
4243
fun `Context is not passed by default between coroutines`() = runBlocking {
4344
ContextMap["myKey"] = "myValue"
@@ -49,6 +50,7 @@ class ThreadContextTest {
4950
}.join()
5051
}
5152

53+
@DelicateCoroutinesApi
5254
@Test
5355
fun `Context can be passed between coroutines`() = runBlocking {
5456
ContextMap["myKey"] = "myValue"
@@ -121,4 +123,16 @@ class ThreadContextTest {
121123
}
122124
}
123125
}
126+
127+
@Test
128+
fun `Context is restored after a context block is complete`() = runBlocking {
129+
assertTrue(ContextMap.empty)
130+
assertTrue(ContextStack.empty)
131+
withContext(CoroutineThreadContext(ThreadContextData(mapOf("myKey" to "myValue"), listOf("test")))) {
132+
assertEquals("myValue", ContextMap["myKey"])
133+
assertEquals("test", ContextStack.peek())
134+
}
135+
assertTrue(ContextMap.empty)
136+
assertTrue(ContextStack.empty)
137+
}
124138
}

0 commit comments

Comments
 (0)