aboutsummaryrefslogtreecommitdiff
path: root/atomicfu/src/jvmTest/kotlin/kotlinx/atomicfu/test/TraceLFTest.kt
blob: 32ea8d85ee1156c947257e38409a84a60319b358 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.atomicfu.test

import kotlinx.atomicfu.*
import kotlin.test.Test

class Counter {
    private val t = Trace(64, TraceFormat { index, text ->
        "$index: [${Thread.currentThread().name}] $text"
    })
    private val a = atomic(0, t)

    fun inc(): Int {
        t { "inc() invoked" }
        val x = a.incrementAndGet()
        t { "inc() = $x" }
        return x
    }

    internal fun get() = a.value
}

class CounterDefaultAtomic {
    private val a = atomic(0)
    private val trace = Trace(64)

    fun inc(): Int {
        trace { "inc() invoked" }
        val x = a.incrementAndGet()
        trace { "inc() = $x" }
        return x
    }

    internal fun get() = a.value
}

class CounterLFTest : LockFreedomTestEnvironment("CounterLFTest") {
    private val c = Counter()
    private val c1 = CounterDefaultAtomic()

    @Test
    fun testCounterDefault() {
        repeat(10) { id ->
            testThread ("Inc-$id")  {
                c1.inc()
            }
        }
        repeat(2) { id ->
            testThread("Get-$id") {
                c1.get()
            }
        }
        performTest(10)
        println(c1.get())
    }

    @Test
    fun testLockFreedom() {
        repeat(10) { id ->
            testThread("Inc-$id") {
                c.inc()
            }
        }
        repeat(2) { id ->
            testThread("Get-$id") {
                c.get()
            }
        }
        performTest(10)
        println(c.get())
    }
}