liveBook · Manning

Thread

As explained in Kotlin in Action, 2E

A thread is an independently schedulable sequence of execution within a process.

A thread is the JVM’s classic unit for running code independently and concurrently. Kotlin remains fully compatible with Java threads and provides a convenient thread function for starting one. section 14.3

import kotlin.concurrent.thread
 
fun main() {
    println("I'm on ${Thread.currentThread().name}")
    thread {                                                  #1
        println("And I'm on ${Thread.currentThread().name}")
    }
}
 
// I'm on main
// And I'm on Thread-0

Start on the main thread, create a second thread with Kotlin’s thread function, and print each thread’s name. section 14.3

Threads can improve responsiveness and distribute work across multicore CPUs, but each JVM thread typically maps to an operating-system thread. Allocation, kernel-level switching, and memory use make threads costly; only a few thousand can usually be managed effectively. section 14.3

Treat threads carefully when work waits or must be coordinated:

  • A thread blocked on a network request cannot perform other meaningful work while waiting. section 14.3
  • Fine-grained or short-lived thread creation is discouraged because creation and management costs accumulate. section 14.3
  • Standalone threads make cancellation, exception handling, and work orchestration harder to manage. section 14.3

Blocking network logic

A sequential showUserInfo function calls login, loadUserData, and showData. If the first two calls wait on the network, the underlying thread remains blocked, limiting request capacity or freezing a user interface. section 14.4.1

Coroutines address this limitation with suspending functions. Marking the network-related functions suspend lets execution pause without blocking the underlying thread, allowing other code to run on it while the response is pending. section 14.4.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains creation, resource costs, blocking, and coordination limits, then stops short of detailed thread lifecycle mechanics.
Examples
Uses Kotlin’s thread function and a sequential login, user-data loading, and display workflow to show creation and blocking.
What it assumes
Assumes basic Kotlin and JVM application knowledge while introducing thread creation, blocking, and suspension through small examples.
What you can do after
Evaluate thread-based designs by identifying resource costs, blocking waits, and coordination difficulties, then compare them with suspending functions.
How it connects
Connects threads with JVM processes, operating-system scheduling, multicore CPUs, blocking I/O, coroutines, cancellation, and exception handling.

Also explained in

Compare how 12 books explain thread →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.