Implementing a Shared Counter

Report a typo

In a multithreaded Kotlin application, you can implement a shared counter using functions to increase and decrease its value.

Consider the following code.

object SharedCounter {
    // ???
    var value: Int = 0
    fun increment() {
        value++
    }
    fun decrement() {
        value--
    }
}

fun main() {
    val threads = List(10) {
        Thread {
            for (i in 1..100) {
                SharedCounter.increment()
                // Set a conditional breakpoint here to trigger when SharedCounter.value is a specific value
                // Use Evaluate Expression to inspect SharedCounter.value
                Thread.sleep(10) // Simulate work
                SharedCounter.decrement()
                // Set a watchpoint on SharedCounter.value
            }
        }
    }
    threads.forEach { it.start() }
    threads.forEach { it.join() }
    println("Final counter value: ${SharedCounter.value}")
    // Use a profiler to check for performance issues
}

Which annotation should you use?

Enter a short text

Create a free account to access the full topic