> Will some thread B calling getLength() ever see [unexpected] results?
It's possible.
Volatiles only preserve their assignment order with other volatiles and
synch blocks, not with assignments to every field in every object (including
the object in which the volatile is declared).
By declaring something as volatile you are specifying that it's state in
shared memory will closely track its state in every thread. Similarly,
synch methods and blocks are used to transmit state between thread working
memory and shared memory.
In your example, it's possible for a reading thread to see that 'init' is
true (reading from shared memory), but not to see the initialized values for
'a' and 'b' -- either because they do not reside in the reading thread's
working memory or because the initializing thread has not written them to
shared memory (yet).
----- Original Message -----
From: "David Smiley" <dsmiley@mitre.org>
To: <javaMemoryModel@cs.umd.edu>
Sent: Thursday, March 29, 2001 6:03 AM
Subject: Re: JavaMemoryModel: JMM problems with latch or copy-on-write?
> You mean something like the following?
>
> Foo foo = new Foo();
> Singleton.FOO = foo;
>
> This situation is like your first example (simple boolean assignment), in
> that the compiler might outsmart you and hide the new foo from other
> threads.
This is distressing. I think I'm starting to understand this better now.
What can be done? Will the proposed semantics of volatile take the problem
away in the copy-on-write case assuming that foo is declared volatile?
As for the latch style problem what about this latch scenario:
class Span{
volatile boolean init= false;//eventually becomes true permanently
int start= 0, end= 0; /* constraint: b >= a */
/* assumed to be called only once ever */
void doInit(int a, int b) {
if (b < a)
throw IllegalArgumentException();
start= a; end=b;
init= true;
}
/* -1 if not ready, the span's length otherwise */
int getLength() {
if (!init)
return -1;
else
return start-end;
}
}
Will some thread B calling getLength() ever see results other than what the
typical programmer would expect? i.e., I'm hoping that there won't be any
funky re-orderings surrounding the init= true.
-- David Smiley
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel
This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:31 EDT