gpt4 book ai didi

java - 如果直接从内存读取 volatile 字段,那么从哪里读取非 volatile 字段?

转载 作者:行者123 更新时间:2023-12-02 05:47:43 29 4
gpt4 key购买 nike

我最近读到 volatile 字段是线程安全的,因为

When we use volatile keyword with a variable, all the threads read its value directly from the memory and don’t cache it

所以这让我想知道,对于非 volatile 字段,线程将从哪里读取其值?我以为一切都存储在内存中。

最佳答案

您引用的说法是一种误解。我推荐以下文章:https://software.rajivprab.com/2018/04/29/myths-programmers-believe-about-cpu-caches/

if volatile variables were truly written/read from main-memory every single time, they would be horrendously slow – main-memory references are 200x slower than L1 cache references. In reality, volatile-reads (in Java) can often be just as cheap as a L1 cache reference, putting to rest the notion that volatile forces reads/writes all the way to main memory. If you’ve been avoiding the use of volatiles because of performance concerns, you might have been a victim of the above misconceptions.

关于java - 如果直接从内存读取 volatile 字段,那么从哪里读取非 volatile 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56080153/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com