The thread that was not started
A easy Java puzzle in the threading and race conditions family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
run executes the runnable directly on the calling thread, like any method. No new thread is created, so the program prints "working in main" and blocks until the task is complete. start creates the thread and calls run on it.
The fix
How to avoid it next time
Call start, never run, to execute work on another thread. Better, submit tasks to an executor.
Want the background? Read Threads and shared state in the Java concepts library.
About threading and race conditions
Without synchronization, threads can see stale values and interleave read-modify-write sequences. A volatile field gives visibility but not atomicity, and check-then-act sequences are never atomic by themselves.
In code review: For every shared variable ask who writes it, who reads it, and what protects it. Prefer atomic classes, concurrent collections and immutable objects.
More puzzles in this family
Frequently asked questions
What is the bug in "The thread that was not started"?
run executes the runnable directly on the calling thread, like any method. No new thread is created, so the program prints "working in main" and blocks until the task is complete. start creates the thread and calls run on it. The faulty line is line 7: worker.run();
How do I fix it?
Replace it with: worker.start();. Call start, never run, to execute work on another thread. Better, submit tasks to an executor.
How do I catch threading and race conditions in code review?
For every shared variable ask who writes it, who reads it, and what protects it. Prefer atomic classes, concurrent collections and immutable objects.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.