Re: reading the JLS (17.4.5)
On 12/21/2011 12:37 AM, Andreas Leitgeb wrote:
Lew<lewbloch@gmail.com> wrote:
Andreas Leitgeb wrote:
Given some (simplified) sample code:
class Test {
/*non-vol*/ int n1;
volatile int v1;
void t1() {
n1 = 1;
v1 = n1; // v1 uses n1
}
void t2() {
int r1=v1, r2=r1*n1; // r2 uses r1
assert ! (r1 == 1&& r2 != 1) : "huh?";
}
}
Two threads T1 and T2 may at some point run t1() and t2()
respectively, then I should expect, per transitivity of
You have to establish a /happens-before/ between the invocations
of t1() an t2().
If two threads begin to execute the methods, you cannot guarantee
that t1() will /happen-before/ t2(), so the read of 'v1' in the
latter could result in the default value.
Perhaps you found the/a sore spot of my (mis?)understanding.
*iff* a *volatile* read gets to see the result of a *volatile*
write, then doesn't that say anything about that the write must
have "happened-before" the read?
In my example, I didn't mean to imply, that r1 would always
turn out to be 1. But *if* it does, then could anything be
assumed about r2 ?
If the write to v1 (but not to n1) in t1() were in a
synchronized(this)-block, and so were the read of v1
(but not n1) in t2(), then would anything be implied
about r2 *if* observing r1 == 1 in T2?
In practice, I think that establishing a happens-before
based on observation of a read's value is quite essential,
but I may of course be wrong here. I don't even see how one
could determine the order in which synchronized blocks for
a common monitor are actually passed through by different
threads, other than by observing reads.
I think we need to distinguish between two things. I'm going to copy
some notation from Lew. /happens-before/, printed in italics in the JLS,
is not an observation about what really happened, but a requirement of
the form "X must appear to happen before Y", with a definition of what
that means in terms e.g. of the results of read operations.
That is entirely distinct from the actual order of operations. If a read
sees the result of a write, that write must have really happened before
(no slashes, no italics) the read, but that does not prove the existence
of a /happens-before/ relationship between them.
However, the volatile reads and writes are synchronization actions, so
they are ordered by the synchronization order, and whichever comes first
in the synchronization order /happens-before/ the other. I agree with
your assertion.
Patricia