On Thu, 18 Feb 2021 07:35:51 GMT, Jaikiran Pai <j...@openjdk.org> wrote:
>> Yes. Once here and once inside `synchronized` block. >> Reading `volatile` fields cost _something_ on some architectures, so I think >> we could optimize it a bit. > > Hello @turbanoff, the double read is necessary to correctly avoid any race > conditions and is a typical strategy used in cases like these. I am not aware > of any other alternate more performant strategy, for code like this. Let me be more clear: I think that it's enough to have only 2 `volatile` field reads _in worst case_. We can use local variable to avoid more than needed reads. Current code can perform read 4 times _in worst case_: twice outside `synchronized` block and twice inside `synchronized` block. There are many examples of similar code in the JDK: https://github.com/openjdk/jdk/blob/master/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Util.java#L48 https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/StackFrameInfo.java#L125 ------------- PR: https://git.openjdk.java.net/jdk/pull/2601