A
A
Alexiuscrow2014-08-18 18:37:30
Java
Alexiuscrow, 2014-08-18 18:37:30

Threads. Why are there different values ​​when starting from under the IDE and the console?

I wanted to implement the "lost update" problem.
Why, when I run the program from under the console, it gives values ​​from 1 billion to 2 billion (as expected), and when I run it from under eclipse, I constantly get 1 billion ?

Source
public class LostUpdate {
  private static int count;
  public static void main(String[] args)  {
    Thread th = new Thread(new Runnable(){
      @Override
      public void run() {
        for(int k = 0; k < 1_000_000_000; k++){
          count++;
        }
      }
    });
    th.start();
    for(int k = 0; k < 1_000_000_000; k++){
      count++;
    }
    try {
      th.join();
    } catch (InterruptedException ignore) {/*NOP*/}
    System.out.println(count);
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bimeg, 2014-08-18
@bimeg

In your example, in addition to the race condition (which you are looking for), there is also a data race. In the presence of a data race, the compiler (and not only) is free to do anything. For example, replace the entire loop with count = 1_000_000_000; It won't break intra-thread semantics. If you put volatile on count, then the data race disappears and only the race condition remains. Then such optimizations are prohibited and you will have to strictly follow what is written. Then you can get any value from [2; 2_000_000_000].
Perhaps something like that. It's very likely that I'm wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question