Re: Mutable Objects and Thread Boundaries
Peter Duniho wrote:
class Test
{
private volatile boolean set = false;
In the above example, if methodA() is executed on one thread, and then
methodB() is executed in a different thread, methodB() is guaranteed to
see the new value for "data".
Yes, for volatile, this works. Volatile fields have special semantics
which prevent re-ordering reads and writes by the compiler, so this is
guaranteed to work.
I said it didn't work for all of the cases Joshua listed, particularily
the synchronized one. Replace the volatile with a synchronized block
and it won't work anymore.
Just trying to let other folks know what works and what doesn't. I
think you knew this already, just that you didn't touch all the bases
when you mentioned it originally.
class Test
{
private boolean set;
private int data;
void methodA()
{
data = 5;
synchronized( this ) {
set = true;
}
}
void methodB()
{
synchronized( this ) {
if (set)
{
System.out.print(data); // may print "0"
}
}
}
}