Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 134 ยท Coroutines

Threads and Java Concurrency

Use threads and the Java concurrency toolbox from Kotlin - thread, ExecutorService, synchronized, atomics, ConcurrentHashMap, CountDownLatch and virtual threads - and learn when coroutines are the better choice.

Coroutines are Kotlin's favorite way to do concurrent work, but they sit on top of something older: threads. Kotlin runs on the JVM, so everything Java offers for concurrency is available to you, and a lot of real code (libraries, frameworks, old projects) still uses it. You need to read that code, call it, and sometimes choose it.

This lesson walks through the Java toolbox with Kotlin syntax: Thread, thread { }, executors and futures, synchronized, atomics, concurrent collections, latches and virtual threads. It ends with an honest comparison with coroutines. It connects to shared mutable state (the problems) and dispatchers (how coroutines use thread pools).

Starting a thread

A thread is an independent flow of execution, scheduled by the operating system. Kotlin's standard library has a helper, thread { }, that creates and starts one. join() waits for it to finish.

Kotlin thread and join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line of output and the second can swap places, because the worker starts at its own pace; the third line always comes last, because join() blocks main until the worker is done. Order between threads that you did not synchronize is never guaranteed. That is also why this lesson's examples always join or wait before printing a final result.

Java's own style, Thread(Runnable) followed by start(), works too. Calling run() by mistake does not start a thread: it executes the code on the current thread. Starting threads by hand is rare today, because each one costs memory (typically about a megabyte of stack reserved) and creation time, and an unlimited number of them can bring a server down.

Exceptions in threads

An uncaught exception ends only the thread that threw it. The JVM prints a message and the rest of the program carries on, which is easy to miss.

Kotlin An exception in another thread (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program prints worker starting, then on stderr a line beginning Exception in thread "worker-1" java.lang.IllegalStateException: disk is full with a stack trace, and finally main is still running. The process exit code is 0: the failure of a background thread does not fail the program. Executors and coroutines give you better ways to receive such errors, as the next sections show.

Thread pools: ExecutorService

Instead of one thread per task, you create a pool of a fixed number of threads and submit tasks to it. The pool reuses its threads. Executors.newFixedThreadPool(n) returns an ExecutorService. Submitting a Callable returns a Future, a handle to a result that will exist later. future.get() blocks until it is ready, and rethrows a failure wrapped in ExecutionException.

Kotlin ExecutorService and Future

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

We read the futures in order, so the output is deterministic even though tasks ran in parallel: tasks 1, 2 and 3 print their squares, task 4 failed: 4 is not allowed, then task 5 -> 25. Three things to remember:

  • Always call shutdown() (on recent Java versions you can also wrap the pool in use { }, as the virtual thread example below does). The threads of a pool are alive until you do, and a non-daemon pool thread keeps the JVM from exiting.
  • future.get() blocks the calling thread. Blocking is cheap in a thread-per-task world, and costly if you do it on a thread that coroutines share.
  • Choose the pool size to match the job: about the number of cores for computation, larger for tasks that mostly wait.

Using a pool with coroutines

An executor can be turned into a coroutine dispatcher with asCoroutineDispatcher(). This is how you bring an existing thread pool into coroutine code:

Kotlin An executor as a coroutine dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is ran on: legacy-pool. Use this when a library hands you an executor, or when you need a dedicated pool for blocking calls that must not starve Dispatchers.Default.

synchronized: mutual exclusion

When threads share a mutable variable, a lock makes sure only one runs a critical section at a time. Kotlin has the function synchronized(lock) { ... }, and an annotation @Synchronized for methods. Both use the JVM monitor of an object.

Kotlin synchronized protects the counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

It prints expected 200000, got 200000. Without the lock the total would often be lower, as shown in shared mutable state. Use a private lock object (Any()) instead of locking on this, so outside code cannot take your lock by accident, and keep the synchronized block short.

Two warnings. First, never put a suspension point inside synchronized; the compiler forbids it, and in coroutine code you want Mutex. Second, two locks taken in different orders by different threads create a deadlock: thread A holds lock 1 and waits for lock 2, thread B holds lock 2 and waits for lock 1, and neither ever moves. Always take multiple locks in the same global order.

Atomics and concurrent collections

For one variable, AtomicInteger and friends are lighter than a lock. For maps and queues shared between threads, java.util.concurrent has ready-made thread-safe versions.

Kotlin ConcurrentHashMap and AtomicLong

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is processed = 24000 and {java=8000, kotlin=12000, scala=4000}. merge does the whole "if absent put 1, else add 1" step atomically for one key. The common mistake is if (!map.containsKey(k)) map[k] = v: each call is safe, but the two together are not, because another thread can slip in between the check and the write. Use merge, compute, computeIfAbsent or Kotlin's getOrPut on a ConcurrentMap.

Other useful pieces: CopyOnWriteArrayList (many reads, rare writes), LinkedBlockingQueue (hand work from producers to consumers; the thread version of a channel), and ConcurrentLinkedQueue.

Waiting for others: CountDownLatch

A CountDownLatch starts with a number. Threads call countDown() when they finish a step, and one or more threads call await() to wait until the count is zero.

Kotlin CountDownLatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is all ready: true and [service-1 started, service-2 started, service-3 started]. The result list is sorted because the threads finish in no fixed order. Always prefer await with a timeout in real code: a thread that dies before countDown() leaves the waiter stuck forever.

Virtual threads

Java 21 added virtual threads: threads scheduled by the JVM instead of the operating system. They are so cheap that you can create hundreds of thousands, and blocking in one (Thread.sleep, a socket read) frees the underlying carrier thread. The programming model is the old, simple one, thread per task, with the scalability of async code.

Kotlin Ten thousand virtual threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program prints finished: 10000. Doing the same with 10,000 platform threads would need gigabytes of stack space and would very likely fail or crawl. use works because ExecutorService is AutoCloseable on recent Java versions, and close() waits for submitted tasks.

Threads or coroutines?

Both give concurrency, and they are not enemies: coroutines run on threads. The difference is in the programming model.

Question Threads (plain Java style) Coroutines
Cost of one unit high for platform threads, low for virtual threads very low (a small object)
Cancellation interrupt(), easily ignored built in, hierarchical
Error handling per thread, easy to lose propagates through the scope tree
Lifetime control manual join and shutdown structured concurrency
Waiting blocking calls suspending calls, thread is freed
Works on JVM only JVM, Android, Native, JS (multiplatform)

Use coroutines for new Kotlin code, especially anything with cancellation, timeouts, many concurrent waits or a multiplatform target. Use threads and executors when a library or framework gives you that API, for a few long-lived background workers, or when you want Java-style code in a mixed project. Use virtual threads when you have a blocking Java codebase and want the scalability without rewriting it into suspend functions. Kotlin coroutines can even run on virtual threads by turning one into a dispatcher.

Blocking inside coroutines

Calling Thread.sleep or a blocking future.get() inside a coroutine holds a thread that other coroutines needed. Wrap blocking calls in withContext(Dispatchers.IO), which has a large pool made for waiting, or use their suspending equivalents (delay, future.await() from the kotlinx-coroutines-jdk8 module).

Common mistakes

  • Calling run() instead of start(), so no new thread appears.
  • Forgetting shutdown() and wondering why the program never exits.
  • Ignoring the result of submit: an exception inside a submitted task is stored in the Future and vanishes if nobody calls get().
  • Synchronizing on a public object, a string literal, or a boxed number.
  • Check-then-act on a concurrent collection.
  • Relying on thread timing in tests; see testing coroutines for the same lesson in coroutine form.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does thread { ... } from kotlin.concurrent do?

    The helper creates and starts the thread (start = true by default). It returns the Thread, so you can join() it.
  2. 2. A task submitted to an ExecutorService throws an exception and nobody calls future.get(). What happens?

    With submit, failures are captured in the Future. Calling get() rethrows them wrapped in ExecutionException.
  3. 3. Which is a correct way to count words from several threads in one ConcurrentHashMap?

    merge performs the read-modify-write for a key atomically. The other forms have a gap between reading and writing.
  4. 4. Why should you avoid synchronized around code that calls a suspend function?

    A monitor belongs to a thread, but a coroutine can change threads at a suspension point. Mutex is built for coroutines.
  5. 5. What is the main advantage of virtual threads?

    Virtual threads are managed by the JVM and blocking in one frees the carrier thread, so tens of thousands of them are practical.

Summary

  • Coroutines run on threads; Java's concurrency tools are fully available in Kotlin.
  • thread { } starts a thread, join() waits; unhandled exceptions kill only that thread.
  • ExecutorService pools threads and returns Futures; always shutdown() and call get() to see failures.
  • synchronized and atomics protect shared state; use merge/compute on concurrent maps instead of check-then-act.
  • CountDownLatch waits for several events; virtual threads make thread-per-task scale.
  • Prefer coroutines for new Kotlin code; use threads when an API or a blocking codebase calls for them, and wrap blocking calls in Dispatchers.IO.

Next: Testing in Kotlin