>I'm not sure I agree with that; the value of the mutable field needs
>to be published safely as well.
Do I read it properly? "you are not sure if java.lang.String is safe"
It is safe since java 1.5.
This is ensured by "17.5 final fields semantics" was added to JMM.
> But Globals.state is not final or volatile.
Here's "safe publication" via data race (Globals.state is not
volatile/synchronized/etc)
Thread 1:
class Globals { public static String state; }
Globals.state = new String(new char[]{'h','e','l','l','o'}); // no
volatile fields involved
Thread 2:
System.out.println(Globals.state); // this _must_ print either null or
"hello".
Note how thread 2 must not print h/he/hel/hell/, even though thread 1
copies characters from one array to another one.
>How does that illustrate what you wrote here: "Just synchronization on the
same lock is not sufficient"
Ok, here's example with synchronizations:
Thread 1:
Globals.str = new StringFromFile();
str.setParameters(...) // this is method is synchronized
Thread 2:
Globals.str.execute() // this method is synchronized
There is no guarantee that execute will observe proper state of
StringFromFile.
For instance, str.execute might be executed before setParameters, then
"setParameters would not happens-before execute", thus there would be no
"safe publication from setParameters to execute".
> True, but that would also affect single threaded code.
The original question was to avoid contention between multiple threads. I
do not think we need spend time on discussing single-threaded executions.
Once again my main point: I am not sure if volatile/synchronized is
required. I would like to dodge non-required synchronization.
​Vladimir