Andremoniy
Andremoniy

Reputation: 34900

Auto optimisation for L cache for object's variables?

Frankly, this is a continue of this my question, inspired by this answer: https://stackoverflow.com/a/53262717/1479414

Let's suppose we have a class:

public class Foo {
    private Integer x;

    public void setX(Integer x) {
       this.x = x;
    }

    public Integer getX() {
       return this.x;
    }
}

And let us consider a very specific scenario, when we have just two threads which interact with the x variable:

At time 1, a thread T1 is created

At time 2, T1 sets the value: foo.setX(123);

At time 3, a thread T2 is created

At time 4, T2 reads the value: foo.getX();

No other threads interact with this value. Both operations happen only once.

So there is no apparent x value read operations before the thread T2 does his job.

The question is: does any auto optimisation for L cache exist which can cache null value of the x variable, so the thread T2 will read its cached value? In other words, do we need the volatile modifier in this particular scenario?

Upvotes: 3

Views: 175

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533530

When you create a thread, it will see any value set before it is created.

In the Javadoc for java.util.concurrency for Java 11 under Memory Visibility Properties and JLS-17.4.5 for Java 8 states

A call to start on a thread happens-before any action in the started thread.

NOTE: A thread only reads a cached value, when it re-reads a value in a cache line it has already in its cache. If it reads a cache line it has never read before or is no longer in a cache, it won't read a stale value.

Upvotes: 4

Nicolas Labrot
Nicolas Labrot

Reputation: 4106

T1 and T2 are executed sequentially and cache is coherent, especially in this sequential use case.

So there is no way that T2 at time 4 will get a null value.

Upvotes: 1

Related Questions