3zmo
3zmo

Reputation: 83

volatile mutable object that doesn't change after assignment

Scenario:

class Foo {

    volatile Bar bar;
}

class Bar {

    int baz;
}

for (int i = 0; i < n; i++) {
    Bar bar = new Bar();
    bar.baz = 1;
    foo.bar = bar;
} 

Is is guaranteed that baz variable will be always visible, if Bar isn't immutable (baz isn't final or volatile) but baz never changes after bar assignment?

Upvotes: 0

Views: 59

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

The volatile is applied only to the variable where you define it.

If you need to be sure that your code works also for nested variables you need to define them volatile too.

As an alternative you can encapsulated the code accessing Bar variable and nested variables in a synchronized block.

The volatile keyword grants that the variable is taken from the main memory instead from the registries of the cpu. This grants that:

… the volatile modifier guarantees that any thread that reads a field will see the most recently written value. - Josh Bloch

This happens to the variable declared volatile, not to the inner fields. You can use the volatile keyword on the baz variable and in this case you are sure that the code works.

Upvotes: 1

Related Questions