Java finality
Jeroen Frijters
jeroen@sumatra.nl
Tue Feb 8 09:49:00 GMT 2005
Mark Wielaard wrote:
> Note that if I read JSR 133 correctly changes to final fields are not
> guaranteed to be seen by other threads ever after the object has been
> constructed completely in the initiating thread.
Not quite. As long as you set the final field before the object
reference escapes the thread, other threads are guaranteed to see the
new value. I think this would be safe, for example:
public Integer createInteger(int val)
{
Integer i = new Integer(0);
Field f = i.getClass().getDeclaredField("value");
f.setAccessible(true);
f.set(i, val);
return i;
}
However, it isn't entirely clear to me whether this code is safe in the
*current* thread. It appears to be legal to move any reads of the final
field to before the reflection code that sets the value, at least that's
what I gather from the discussion of "final field safe contexts".
Regards,
Jeroen
More information about the Java
mailing list