[concurrency-interest] Relativity of guarantees provided by volatile

Gregg Wonderly gregg at cytetech.com
Wed Aug 22 14:15:03 EDT 2012

On 8/22/2012 12:18 PM, Zhong Yu wrote:
> On Wed, Aug 22, 2012 at 1:39 AM, Marko Topolnik <mtopolnik at inge-mark.hr> wrote:
>> On 22. kol. 2012., at 01:40, Boehm, Hans wrote:
>>>> From: Marko Topolnik [mailto:mtopolnik at inge-mark.hr]
>>>>> Similar to your concern that consecutive volatile writes can be
>>>>> compressed into the last write, it also seems true that consecutive
>>>>> volatile reads can be compressed into the first read - exactly the
>>>>> kind of optimization to be disabled by C's volatile. It's
>>>>> inconceivable that any JVM will do such optimization on volatile
>>>>> reads, it'll break lots of programs, e.g. busy waits.
>>>> Actually there is already a provision in the JMM (in the original
>>>> paper, at least) that prevents a busy-waiting loop whose condition
>>>> involves a volatile read to forever read a stale value. There can be
>>>> only a finite number of such read actions. But, this is a small
>>>> consolation, really. Most code DOES make a difference between "eternity
>>>> minus one" and "right now".
>>> My recollection is that this is only sort of/mostly of true.  If your entire program consists of
>>> Thread 1:
>>> while (!flag) {}
>>> Thread 2:
>>> flag = true;
>>> There is intentionally no requirement that thread 2 ever be scheduled.  If it's not, that looks a lot like flag having been read once.  If, on the other hand, thread 2 sets flag and then prints "Hello", and you see the "Hello", then I believe you are correct that thread 1 must terminate.
>> If thread 2 never gets scheduled then the value of the flag is not stale (that's what I said---"read a stale value"). This JMM provision
> Can you give the reference to this provision? (I didn't see an
> explicit one; though it's quite natural, since the set of actions
> should be countable)
> precludes bunching together an infinite amount of busy-wait flag
> checks, all reading the stale false value.

Java provides for no guarantees that the host operating system will actually, 
effectively (for you), schedule any thread other than the current one, with any 
reliability.  It just states when a thread is running, this is the behavior you 
will perceive based on the JLS and JMM.

So, Thread.yield()'s necessity of use is unspecified.  But there were some early 
JVMs which did require the use of Thread.yield because the thread scheduling 
and/or os were not preemptive.


More information about the Concurrency-interest mailing list