In ArrayBlockingQueue, why copy final member field into local final variable?

后端 未结 2 687
借酒劲吻你
借酒劲吻你 2020-11-22 04:56

In ArrayBlockingQueue, all the methods that require the lock copy it to a local final variable before calling lock().

         


        
相关标签:
2条回答
  • 2020-11-22 05:17

    This thread gives some answers. In substance:

    • the compiler can't easily prove that a final field does not change within a method (due to reflection / serialization etc.)
    • most current compilers actually don't try and would therefore have to reload the final field everytime it is used which could lead to a cache miss or a page fault
    • storing it in a local variable forces the JVM to perform only one load
    0 讨论(0)
  • 2020-11-22 05:39

    It's an extreme optimization Doug Lea, the author of the class, likes to use. Here's a post on a recent thread on the core-libs-dev mailing list about this exact subject which answers your question pretty well.

    from the post:

    ...copying to locals produces the smallest bytecode, and for low-level code it's nice to write code that's a little closer to the machine

    0 讨论(0)
提交回复
热议问题