Skip to the page

Concurrency · core

Threads, states and wait/notify

A thread has six states. Reading them in a thread dump tells you where a service is stuck. wait and notify coordinate threads, and always need a while loop.

The notes

What you must know

  • The six states of Thread.State: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.
  • BLOCKED: waiting to enter a synchronized block held by another thread. Many BLOCKED threads on one object mean lock contention.
  • WAITING: Object.wait(), join(), or parked by LockSupport.park (ReentrantLock, BlockingQueue.take, Future.get). TIMED_WAITING: sleep, wait or park with a timeout.
  • RUNNABLE also covers a thread blocked in native I/O such as a socket read: the JVM cannot tell it is waiting.
  • start() makes a new thread. run() just runs the method on the current thread. Starting a thread twice throws IllegalThreadStateException.
  • wait releases the monitor and must be called while holding it, or IllegalMonitorStateException is thrown. sleep keeps every lock it holds.
  • Use while, not if, around wait: spurious wakeups, and waking when it is not your turn.
  • Odd and even printing: a shared lock and counter, or a Semaphore for each thread, or a ReentrantLock with one Condition per thread. The last thread must notify so the other does not wait forever. Producer and consumer: ArrayBlockingQueue(100): put blocks when full, take blocks when empty. Stop consumers with one poison pill each. On InterruptedException restore the flag. Take dumps with jcmd <pid> Thread.print or jstack <pid>, two or three dumps a few seconds apart.

The red pen

Common traps: mistake → fix

  • Mistake: run() starts a new thread

    Fix: only start() does.

  • Mistake: sleep releases locks

    Fix: sleep keeps them; wait releases the monitor.

  • Mistake: if (condition) wait() is enough

    Fix: use while because of spurious wakeups.

Easy to hard

Questions interviewers ask, easy to hard

  1. What states can a Java thread be in?
  2. What is the difference between start and run?
  3. What is the difference between wait and sleep?
  4. Write two threads that print odd and even numbers in order.
  5. Write a producer-consumer with a bounded buffer.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview