volatile variables and memory barrier in java

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

    Making the next field volatile would impose a memory barrier on all instances of the node class, not just the root node. I'd expect that to be more expensive than just using synchronized on the root node. In addition, the JVM may be able to optimize synchronized method calls far better. See also this and this.

    That said, you should probably try both and benchmark/profile to see what happens.

提交回复
热议问题