If a synchronized method throws an exception, do member writes made in it prior to that throw become visible to other threads? E.g.
class Foo
{
private int x;
public synchronized void foo()
{
x++;
// some other code using x that throws RTE for a specific thread
}
}
If an object of Foo is shared between threads t1 and t2, and t1 throws an exception as shown, in that case will the latest value of x be flushed to main memory so that it’s visible to t2 when it enters foo for that object?
Yes, changes will still be visible – you’re still exiting the synchronized block, releasing the monitor in the process, and the memory model doesn’t care how that occurs – just that it does occur. It’s still an “unlock action on a monitor” in the terms of JLS section 17.4.4, so it synchronizes with the next action on the same monitor.