Auto optimisation for L cache for object's variables?
Asked Answered
A

2

3

Frankly, this is a continue of this my question, inspired by this answer: https://mcmap.net/q/15885/-cdi-postconstruct-and-volatile-fields

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?

Ardra answered 12/11, 2018 at 13:50 Comment(0)
G
4

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.

Gethsemane answered 12/11, 2018 at 18:39 Comment(2)
Thank you a lot for your answer! It sounds logical that when a new thread is created it should see the actualised value of any variable. However, could this statement be strengthened with some links to the specification?Ardra
@Ardra I have added a quote.Gethsemane
C
1

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.

Crocker answered 12/11, 2018 at 14:38 Comment(5)
So you assume that the CPU cache has nothing to do with volatile-problem?Ardra
I do not assume that. I assume that because the execution of T1 and T2 is sequential, the cache will be coherent (no concurrency issue)Crocker
That was my question: some people claim that there exist an auto optimisaiton which acts independently of existent threadsArdra
Could you please elaborate?Crocker
I don't know how to elaborate. It was said that there is a "auto optimisation for L* cache" which can cause the null value be cached and passed therefore to the thread T2. That was my question: does something similar really exist?Ardra

© 2022 - 2024 — McMap. All rights reserved.