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