volatile piggybacking

Volatilty piggybacking is the (dubious ?) technique which attributes volatile-like semantics to non-volatile variables.

The new memory model , from java 5, states that "a write to a volatile field (§ happens-before every subsequent read of that field".

i.e writing to a volatile field creates a memory fence, which will flush the data held in memory cache, so that anything visible to the thread writing to a volatile field becomes visible to any other thread reading that same field. 

The "anything" in the sentence above might be a non-volatile variable - which will end up being visible to all threads in the same way the volatile which initially triggered the memory fence is. Thus the former piggybacks on the memory flush triggered by the later.

Examples of this technique in core jdk classes are hard to come by (ie. I havent found any...) . Possibly a reflection on how fragile that technique is. 

1 comment:

  1. ouch, did I understand it right, that data can be accessed externally and thus allowing eavesdropping on volatile data? Is this considered as a -will fix- bug or just as an unsafe technique?

    P.S. I'm a slow reader, took a while to read this post :D