Kotlin threads, AtomicInteger, and an executor

Kotlin can use JVM threads directly. thread { ... } from kotlin.concurrent starts a new thread, and join waits for it. When several threads change the same variable, plain increments can be lost, because count++ is a read, an add, and a write. AtomicInteger.incrementAndGet performs the whole update as one atomic step, so four threads adding 50000 each always end at 200000.

Kotlin
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread

fun main() {
    val counter = AtomicInteger(0)
    val threads = List(4) {
        thread {
            repeat(50_000) { counter.incrementAndGet() }
        }
    }
    threads.forEach { it.join() }
    println("counter = ${counter.get()}")

    val pool = Executors.newFixedThreadPool(4)
    val futures = (1..4).map { part ->
        pool.submit(Callable { ((part - 1) * 250 + 1..part * 250).sumOf { it.toLong() } })
    }
    println("sum = ${futures.sumOf { it.get() }}")
    pool.shutdown()
}
Read the full lesson