Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7186671
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T18:40:51+00:00 2026-05-28T18:40:51+00:00

I am slightly surprised by what I get if I compile and run the

  • 0

I am slightly surprised by what I get if I compile and run the following (horrible non-synchronized) Java SE program.

public class ThreadRace {

    // this is the main class.

    public static void main(String[] args) {

        TestRunnable tr=new TestRunnable(); // tr is a Runnable.
        Thread one=new Thread(tr,"thread_one");
        Thread two=new Thread(tr,"thread_two");

    one.start();
    two.start(); // starting two threads both with associated object tr.
    }
}

class TestRunnable implements Runnable {
    int counter=0; // Both threads can see this counter.

    public void run() {
    for(int x=0;x<1000;x++) {
        counter++;
    }
        // We can't get here until we've added one to counter 1000 times.
        // Can we??

    System.out.println("This is thread "+
      Thread.currentThread().getName()+" and the counter is "+counter);
    }
}

If I run “java ThreadRace” at the command line, then here is my interpretation
of what happens. Two new threads are created and started. The threads have
the same Runnable object instance tr, and so they see the same tr.counter .
Both new threads add one to this counter 1000 times, and then print the value
of the counter.

If I run this lots and lots of times, then usually I get output of the form

This is thread thread_one and the counter is 1000
This is thread thread_two and the counter is 2000

and occasionally I get output of the form

This is thread thread_one and the counter is 1204
This is thread thread_two and the counter is 2000

Note that what happened in this latter case was that thread_one finished
adding one to the counter 1000 times, but thread_two had started adding
one already, before thread_one printed out the value of the counter.
In particular, this output is still comprehensible to me.

However, very occasionally I get something like

This is thread thread_one and the counter is 1723
This is thread thread_two and the counter is 1723

As far as I can see, this “cannot happen”. The only way the System.out.println() line
can be reached in either thread, is if the thread has finished counting to 1000.
So I am not bothered if one of the threads reports the counter as being some
random number between 1000 and 2000, but I cannot see how both threads can
get as far as their System.out.println() line (implying both for loops have finished,
surely?) and counter not be 2000 by the time the second statement is printed.

Is what is happening that both threads somehow attempt to do counter++ at exactly
the same time, and one overwrites the other? That is, a thread can even be
interrupted even in the middle of executing a single statement?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T18:40:53+00:00Added an answer on May 28, 2026 at 6:40 pm

    The “++” operator is not atomic — it doesn’t happen in one uninterruptible cycle. Think of it like this:

    1. Fetch the old value
    2. Add one to it
    3. Store the new value back
    

    So imagine that you get this sequence:

    Thread A: Step 1
    Thread B: Step 1
    Thread A: Step 2
    Thread B: Step 2
    Thread A: Step 3
    Thread B: Step 3
    

    Both threads think they’ve incremented the variable, but its value has only increased by one! The second “store back” operation effectively cancels out the result of the first.

    Now, truth is, when you add in multiple levels of cache, far weirder things can actually happen; but this is an easy explanation to understand. You can fix these kinds of issues by synchronizing access to the variable: either the whole run() method, or the inside of the loop using a synchronized block. As Jon suggests, you could also use some of the fancier tools in java.util.concurrent.atomic.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In studying for the OCP Java Programmer Exam, I was slightly surprised to see
I slightly modified a server-client Twisted program on this site, which provided a program
A slightly archaic question I'm afraid but here goes: I have a program which
I slightly remember that there is an class which is capable of stretching an
I have a couple slightly modified / non-traditional setups for feedforward neural networks which
I've created a domain class in Grails like this: class MyObject { static hasMany
Another slightly non-technical question, but I couldn't decide whether to ask here or on
Although slightly related to a previous question, it is different. How secure is this
I slightly remember from my age old Java days, that there was an RequestScope
I am using a slightly modified version of this code . to create a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.