Two threads, one variable
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Shared data is any data that two or more threads can reach at the same time. All threads of a Java program use the same heap, so one object can be changed by many threads at once, and without care the result can be wrong.
Heap objects are shared, local variables are not
A race condition is a bug where the result depends on the timing of threads that share data, so the program can give different answers on different runs.
Every object made with new lives on the heap, one memory area that all threads of a program share. If two threads hold a reference to the same object, they read and write the very same fields.
Example 1 · Both threads see the same object
class NoticeBoard { String message = "No notice yet";}
public class SharedHeapDemo { public static void main(String[] args) throws InterruptedException { NoticeBoard board = new NoticeBoard(); // one object on the heap
Thread writer = new Thread(() -> { String draft = "Fest on Friday"; // local: only this thread has it board.message = draft; // changes the shared object }, "writer");
Thread reader = new Thread(() -> { String seen = board.message; System.out.println(Thread.currentThread().getName() + " sees: " + seen); }, "reader");
writer.start(); writer.join(); reader.start(); reader.join(); System.out.println("main sees: " + board.message); }}reader sees: Fest on Friday main sees: Fest on Friday
What this code does
- There is only one
NoticeBoardobject. The writer thread changes its field, and the reader thread andmainboth see that change, because all three hold a reference to the same object on the heap. draftandseenare local variables, so each lives only on its own thread's stack. The threads here take turns (the reader starts afterwriter.join()), so the output is the same on every run.
Example 2 · Local variables: one copy per thread
public class LocalCopiesDemo { static void countTickets(int[] results, int slot) { int sold = 0; // local: each thread has its own for (int i = 0; i < 1_000_000; i++) { sold++; } results[slot] = sold; // each thread writes only its own slot }
public static void main(String[] args) throws InterruptedException { int[] results = new int[2]; Thread a = new Thread(() -> countTickets(results, 0), "counter-1"); Thread b = new Thread(() -> countTickets(results, 1), "counter-2"); a.start(); b.start(); a.join(); b.join(); System.out.println("counter-1 sold: " + results[0]); System.out.println("counter-2 sold: " + results[1]); System.out.println("Total: " + (results[0] + results[1])); }}counter-1 sold: 1000000 counter-2 sold: 1000000 Total: 2000000
What this code does
- Both threads run
countTicketsat the same time, yet each gets exactly 1,000,000. Each call has its ownsoldon its own stack, so the threads never touch each other's count. - The
resultsarray is shared, but each thread writes a different element andmainreads them only after bothjoin()calls. Giving each thread its own data and combining afterjoin()is the simplest way to avoid a race.
Each thread also has its own stack, a private memory area for its method calls. Local variables and parameters live there, so two threads running the same method get separate copies. A local variable that holds a reference is private, but the object it points to can still be shared. Static fields are shared too: there is one copy per class, not per thread.
- Shared: fields of an object that both threads can reach, and static fields.
- Not shared: local variables and parameters. Each thread has its own copy.
- Careful: a private local reference can point to a shared object.
Two threads updating one counter
A shared counter is one field that several threads add to. When two threads update it at the same time, some of the additions can disappear.
Example 3 · Two threads, one counter: updates go missing
class Counter { int count = 0;
void increment() { count++; }}
public class SharedCounterDemo { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); // one object, shared by both threads Runnable task = () -> { for (int i = 0; i < 1_000_000; i++) { counter.increment(); } }; Thread a = new Thread(task, "adder-1"); Thread b = new Thread(task, "adder-2"); a.start(); b.start(); a.join(); b.join(); System.out.println("Expected: 2000000"); System.out.println("Actual: " + counter.count); }}Expected: 2000000 Actual: 1346782
What this code does
- Both threads call
increment()on the sameCounter, so they change the samecountfield. The actual number is different on every run and is usually below 2,000,000; once in a while it can be exactly right. - Compare this with Example 2: the loop is the same, but there each thread counted in its own local variable and nothing was lost.
In the program above each thread adds 1 a million times, so the answer should be 2,000,000. On a normal multi-core computer it is usually less, and the number changes from run to run. Now and then a run comes out right, which makes the bug easy to miss. Both join() calls finish before the count is printed. So the missing additions are not caused by reading too early: they were really lost. The next lesson shows step by step how.
A railway reservation counter as an analogy
A lost update happens when one write overwrites another, so a change disappears. A railway reservation office with two clerks and one paper chart shows it well.
Example 4 · Two clerks, one sales chart (a static field)
class Clerk implements Runnable { static int ticketsSold = 0; // static: one copy shared by every Clerk
private final int toSell; // instance field: each Clerk has its own
Clerk(int toSell) { this.toSell = toSell; }
@Override public void run() { for (int i = 0; i < toSell; i++) { ticketsSold++; // read the chart, add one, write it back } }}
public class ReservationChartDemo { public static void main(String[] args) throws InterruptedException { Thread clerk1 = new Thread(new Clerk(1_000_000), "clerk-1"); Thread clerk2 = new Thread(new Clerk(1_000_000), "clerk-2"); clerk1.start(); clerk2.start(); clerk1.join(); clerk2.join(); System.out.println("Tickets handed out: 2000000"); System.out.println("Chart says: " + Clerk.ticketsSold); }}Tickets handed out: 2000000 Chart says: 1573905
What this code does
- The two threads run two different
Clerkobjects, yet they still shareticketsSold, because a static field belongs to the class, not to an object. Each clerk'stoSellis a separate instance field and is not shared. - The chart number changes from run to run and is usually lower than the tickets handed out; some runs can still come out right. A million tickets per clerk is not realistic; the large number only makes the overlap easy to see.
The chart says "Tickets sold: 41". Both clerks read 41 at the same moment. Each sells one ticket and writes 42 on the chart. Two tickets went out, but the chart moved up by only one. Neither clerk made a mistake on their own: the problem is that they read and wrote the same chart without taking turns. Threads behave like these clerks. The program above uses a static field as the chart, to show that static fields are shared in exactly the same way.
What a race condition is
A race condition is a bug where the result depends on the timing of threads: which one runs first and how their steps mix. The threads "race" each other, and the result depends on who wins.
Example 5 · Remove one ingredient and the race is gone
class Counter { int count = 0;}
public class RaceIngredientsDemo { static void runBoth(Runnable task) throws InterruptedException { Thread a = new Thread(task, "worker-1"); Thread b = new Thread(task, "worker-2"); a.start(); b.start(); a.join(); b.join(); }
public static void main(String[] args) throws InterruptedException { // 1. Shared and written by both threads: a race Counter shared = new Counter(); runBoth(() -> { for (int i = 0; i < 1_000_000; i++) { shared.count++; } }); System.out.println("Shared and written: " + shared.count + " (should be 2000000)");
// 2. Not shared: each thread counts locally, then stores its own slot int[] parts = new int[2]; Thread p1 = new Thread(() -> { int n = 0; for (int i = 0; i < 1_000_000; i++) n++; parts[0] = n; }, "worker-1"); Thread p2 = new Thread(() -> { int n = 0; for (int i = 0; i < 1_000_000; i++) n++; parts[1] = n; }, "worker-2"); p1.start(); p2.start(); p1.join(); p2.join(); System.out.println("Not shared: " + (parts[0] + parts[1]));
// 3. Shared but only read: both threads add up the same marks int[] marks = {78, 91, 66, 85, 92}; int[] sums = new int[2]; Thread r1 = new Thread(() -> { for (int m : marks) sums[0] += m; }, "reader-1"); Thread r2 = new Thread(() -> { for (int m : marks) sums[1] += m; }, "reader-2"); r1.start(); r2.start(); r1.join(); r2.join(); System.out.println("Shared, only read: " + sums[0] + " and " + sums[1]); }}Shared and written: 1384021 (should be 2000000) Not shared: 2000000 Shared, only read: 412 and 412
What this code does
- Only case 1 has all three ingredients: shared data, threads that write it, and no taking turns. Its number changes from run to run; cases 2 and 3 print the same result every time.
- In case 3 the
marksarray is shared, but no thread changes it, so both readers always get 412. Each reader writes only its own slot ofsums. On a very busy computer case 1 may come out right on some runs, so try it a few times.
- Do not share: give each thread its own data and combine the results after
join(). - Do not change: data that nobody modifies after the threads start is safe to read from many threads.
- Take turns: make threads use the data one at a time. The
synchronizedlessons in this module show how.
Three things together cause one. The same data is reachable from two or more threads, at least one thread changes it, and nothing makes the threads take turns. Remove any one of these and that race is gone.
Next step
Check your understanding
10 quick questions