• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package kotlinx.coroutines
2 
3 import kotlinx.coroutines.testing.*
4 import kotlinx.coroutines.exceptions.*
5 import kotlinx.coroutines.internal.*
6 import kotlin.test.*
7 
8 class CommonThreadLocalTest: TestBase() {
9 
10     /**
11      * Tests the basic functionality of [commonThreadLocal]: storing a separate value for each thread.
12      */
13     @Test
<lambda>null14     fun testThreadLocalBeingThreadLocal() = runTest {
15         val threadLocal = commonThreadLocal<Int>(Symbol("Test1"))
16         newSingleThreadContext("").use {
17             threadLocal.set(10)
18             assertEquals(10, threadLocal.get())
19             val job1 = launch(it) {
20                 threadLocal.set(20)
21                 assertEquals(20, threadLocal.get())
22             }
23             assertEquals(10, threadLocal.get())
24             job1.join()
25             val job2 = launch(it) {
26                 assertEquals(20, threadLocal.get())
27             }
28             job2.join()
29         }
30     }
31 
32     /**
33      * Tests using [commonThreadLocal] with a nullable type.
34      */
35     @Test
<lambda>null36     fun testThreadLocalWithNullableType() = runTest {
37         val threadLocal = commonThreadLocal<Int?>(Symbol("Test2"))
38         newSingleThreadContext("").use {
39             assertNull(threadLocal.get())
40             threadLocal.set(10)
41             assertEquals(10, threadLocal.get())
42             val job1 = launch(it) {
43                 assertNull(threadLocal.get())
44                 threadLocal.set(20)
45                 assertEquals(20, threadLocal.get())
46             }
47             assertEquals(10, threadLocal.get())
48             job1.join()
49             threadLocal.set(null)
50             assertNull(threadLocal.get())
51             val job2 = launch(it) {
52                 assertEquals(20, threadLocal.get())
53                 threadLocal.set(null)
54                 assertNull(threadLocal.get())
55             }
56             job2.join()
57         }
58     }
59 
60     /**
61      * Tests that several instances of [commonThreadLocal] with different names don't affect each other.
62      */
63     @Test
testThreadLocalsWithDifferentNamesNotInterferingnull64     fun testThreadLocalsWithDifferentNamesNotInterfering() {
65         val value1 = commonThreadLocal<Int>(Symbol("Test3a"))
66         val value2 = commonThreadLocal<Int>(Symbol("Test3b"))
67         value1.set(5)
68         value2.set(6)
69         assertEquals(5, value1.get())
70         assertEquals(6, value2.get())
71     }
72 }
73