volatile variables and memory barrier in java

后端 未结 3 612
北恋
北恋 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:06

    Your root node actually does not need to be a node. You only need a reference to the first "real" node.

    public class LinkedList {
      private volatile Node firstNode;
      ...
      addNode(Node node) {
        node.next = firstNode;
        firstNode = node;
      }
    }
    

    So you don't need to make the next field volatile in all your nodes; the nodes are not synchronized at all. You could use that class for the non-synchronized linked lists if you don't mind the cost of the volatile access to the first node. Or you could instead simply rewrite the class with a non-volatile firstNode for the non-synchronized version.

提交回复
热议问题