Re: JavaMemoryModel: Unsynchronized read as an optimization

From: Robert Munyer (munyer@digi-net.com)
Date: Fri Dec 15 2000 - 14:30:11 EST


On 12/15/00, Bill Pugh <pugh@cs.umd.edu> wrote:
> At 1:50 PM -0500 12/15/00, Robert Munyer wrote:

>> I've been discussing double-check with the author of a high-performance Java
>> web server I'm evaluating. He believes unsynchronized read is safe in the
>> majority of JVM installations (even if you only count servers)
>
> Doesn't matter. Real Java programmers don't write code that runs
> correctly only on a majority of platforms.
>
>> and he would
>> like to have an optimization setting to take advantage of this feature.
>
> Use volatile. On platforms with strong memory models, the performance
> hit from using volatile will be insignificant.

Yes, it occurred to me that a solution involving volatile would be better.
The decision of whether to synchronize would be under the control of the JVM
developer, instead of the server administrator. Definitely an improvement.

BUT I was not able to think of any idiom using volatile that would work
correctly according to the JLS. If I understand the rules of Chapter 17
correctly, the only way to get volatile to work correctly in the code below
would be to add a volatile modifier to EVERY variable that is visible
through the variable "helper." All of its members, all of its members'
members, all of its superclasses' members -- all these variables would have
to be declared volatile. Or did I miss something when I read Chapter 17?

>> After some thought, I think the idiom below will serve this purpose. I want
>> to ask two questions of the experts on this list: (1) Is this code correct?
>> And if the answer to #1 is yes: (2) Can you give me an idea of which JVMs
>> (current and imminent) will be unable to take advantage of the optimization?
>
> The code belong is wrong. It will not work correctly on SMP's with
> weak memory models, such as the COMPAQ Alpha.

Do you mean it will not work correctly, regardless of the value of the
optimization flag? Or do you mean it will not work correctly if the flag is
set to 'true' on those machines?

>> class Foo {
>> private Helper helper = null;
>> private boolean helperExists;
>> public Helper getHelper() {
>> if (!helperExists)
>> synchronized(this) {
>> if (helper == null)
>> helper = new Helper();
>> else
>> helperExists = GlobalSettings.ALLOW_UNSYNCHRONIZED_READ;
>> }
>> return helper;
>> }
>> // other functions and members...
>> }

-- Robert Munyer <munyer@digi-net.com>

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:29 EDT