3

When I create a new object in a thread which is an attribute of an object I´am giving to the thread it stays null in the main-function (but just without the System.out). I wrote a simple example of my Problem, which has the same result:

public class T1 {
    public T2 t2;
}
public class T2 {
    public String s;
    /**
     * @param args
     */
    public static void main(String[] args) {
        T1 t1 = new T1();

        T3 thread = new T3(t1);
        thread.start();

        while(t1.t2 == null){
    //      System.out.println("null");
        }
        System.exit(0);
    }
}

public class T3 extends Thread{
    public T1 t1;

    public T3(T1 t1){
        this.t1 = t1;
    }

    @Override
    public void run(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.t2 = new T2();
        while(true){
            System.out.println(t1.t2);
        }
    }
}

So without System.out.println("null") it results in an infinite loop, but when I add this System.out it behaves like I suspect. I even get the same result or problem if I use static variables.

Is there some sort of optimization or something else I don´t understand? Or why is t1.t2 always == null without System.out.println("null")? I thought the T1-object and his attributes (in this case the object t2) will be created on the heap, which is shared between all threads and just the t1-reference-variable is stored on the stack. So hopefully someone can explain me, why it stays null without the System.out... The problem just occurs if the thread is executed after the while-loop, thats why there is a sleep(1000).

1

1 Answer 1

15

So without System.out.println("null") it results in an infinite loop, but when I add this System.out it behaves like I suspect. I even get the same result or problem if I use static variables.

If a thread is updating a value that another thread is reading, there must be some sort of memory synchronization. When you add the System.out.println(...) this uses the underlying PrintStream which is a synchronized class. So the call to println(...) is what synchronizes the memory between the threads.

Here's some good information around memory synchronization from Oracle.

You should add volatile to the T2 t2; field to have the updates to t2 be visible between threads.

The real problem here is that with a modern multi-CPU (and core) hardware, each CPU has its own high speed memory caches. Modern OS and JVM software makes use of these physical (and virtual) CPUs to schedule threads to run in parallel simultaneously. These caches are a critical part of threading performance. If every read and every write had to go to central storage, your application would run 2+ times order of magnitude slower. The memory synchronization flushes the cache so that local writes getting written to central storage, and local cached reads are marked dirty so they have to be re-read from central storage when necessary.

8
  • 2
    Another good read: docs.oracle.com/javase/6/docs/api/java/util/concurrent/…
    – JB Nizet
    Jun 3, 2013 at 18:37
  • thank you very much. So am I right, that my problem has to do with the happens-before relationship? Does the JVM re-orders the operations, so that the write (t1.t2 = new T2()) comes after all reads(while(t1.t2==null))? Or is it just optimizing the code with the assumption that since it never changes the value, it doesn't need to read it from memory? Or is it just always reading an old value? I tought that there is a global heap (or whatever) where all objects get read from.
    – Henrik
    Jun 3, 2013 at 21:01
  • 1
    No, not quite. There is a global heap but the problem is that the CPUs each have memory caches. It's less about optimizations although that may contribute. I've added some more to my answer @user2448967.
    – Gray
    Jun 3, 2013 at 21:05
  • 1
    One essential remark I'm missing in this answer here is: never do anything remotely like this in production code!
    – iwein
    Jun 3, 2013 at 21:15
  • 1
    @Gray final AtomicBoolean flag = new AtomicBoolean(false); saves about three fairies I think. Doing the sharing of volatile primitives right is possible but not worth the effort of documenting it every time. I'm not saying I don't like your answer by the way, I even voted for it, I think it would be better if it steered people away from the general idea :)
    – iwein
    Jun 4, 2013 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.