-2

So i m currently trying to understand concurrency. In my code I created a class "Summer" that features an int var. Its methode sumUP increments var by 2000000. My 2nd class is a Thread that takes Summer as an argument and calls its method sumUp. Both objects are initialized and started in my main Thread.

After my understanding the result should be arbitrary, basically giving my random numbers. The main Thread and the 2nd Thread create their own copy of the variable and change it independently.

My code is not Thread Safe at all, no volatile, no synchronized and still the answer is always 4000000. Can you please explain to my my error or is eclipse fixing Thread safety for me ? Thanks in advance :)

public class Main {

public static void main(String[]agrs) {

    Summer summer = new Summer();

    Thread t1 = new Thread(new MyRunnable(summer));

    summer.sumUp();
    t1.start();
}


}


public class MyRunnable implements Runnable {

private Summer summer;

public MyRunnable(Summer summer) {
    this.summer = summer;
}

@Override
public void run() {

    System.out.println(Thread.currentThread().getName() + " hat gestartet R");

    summer.sumUp();

    System.out.println("Thread val =" + summer.val);

}

}


public class Summer {

public int val;

public void sumUp() {
    for(int i=0; i<2000000; i++) {
        increment();
    }

    System.out.println("MainThread val = " + val);
}

private void increment() {
    val++;
}

}

(I know var should be private but it was quicker that way :) )

Coldvirus
  • 45
  • 10
  • 1
    This is nothing to do with Eclipse which is just your development environment. This question is about how Java works. – greg-449 Jan 29 '18 at 16:01

2 Answers2

3

You only start the thread after the first run of sumUp finished, leaving the value at 2000000. You might experience the "desired" problems by starting the thread first.

PS: This has nothing to do with Eclipse.

C-Otto
  • 5,615
  • 3
  • 29
  • 62
3

Thread.start creates a "Happens before relation". Quote from this Question.

When a statement invokes Thread.start(), every statement that has a happens-before relationship with that statement also has a happens-before relationship with every statement executed by the new thread. The effects of the code that led up to the creation of the new thread are visible to the new thread

So when the thread cache is initialized, the value of summer is already 2000000.

kai
  • 6,702
  • 22
  • 38
  • 1
    Best answer because it actually explains where the synchronization is. Note that this is an API feature, not actually part of the language. `java.util.concurrency` also has a lot of classes that specify a happens-before relationship. – markspace Jan 29 '18 at 16:46