volatile variables and memory barrier in java

后端 未结 3 611
北恋
北恋 2021-02-03 13:26

I\'ve got a data structure which consists of linked nodes. You can think of it as of a simple LinkedList. Each node of the list consists of some value and a next field pointing

3条回答
  •  一生所求
    2021-02-03 14:11

    1.

    Based on what you say here

    constructing a new object, setting its fields and setting the next field to the object pointed by the root, then setting the root's next field to this new node.

    Then yes, setting the next field to volatile will correctly synchronize. Its important to understand why. You have three sets of writes before hand, the one to the node object, one to the fields and one to the nodes next (though not completely sure why you are doing that, maybe I miss understand something).

    So that's 2 + (N number of field) writes. At this point there is no happens-before relationship and if the node is written normally there is no guarantee. As soon as you write to the volatile field all previous writes will now also be visible.

    2.

    Volatile reads/writes on a x86 (or any cache-coherent) operating system has the following attributes:

     volatile-read: very close to a normal read
     volatile-write: about 1/3 the time of a synchronization write 
             (whether within intrinsic locking or  j.u.c.Lock locking)
    

    3.

    Looks like you will have to create VolatileNode and Node. There was a proposal for Java 7 to come out with a Fences API which you can specify which style of reading/write you want to execute with a static utility class but doesn't look like its releasing

    Edit:

    Thkala made a great point I feel is worth including

    although it should be pointed out that pre-JSR133 JVMs (i.e. Java < 5.0) did not have the same semantics

    So what I wrote does not apply to applications run in Java 1.4 or less.

提交回复
热议问题