java多线程缓存_java – 线程的多线程访问和变量缓存

问题是java只是一个规范.有许多JVM实现和物理操作环境的示例.在任何给定的组合上,动作可能是安全的或不安全的.例如,在单处理器系统上,示例中的volatile关键字可能完全没必要.由于存储器和语言规范的编写者无法合理地考虑可能的操作条件集,因此他们选择将某些模式列入白名单,这些模式可以保证适用于所有兼容的实现.遵守这些准则可确保您的代码可以在目标系统上运行,并且可以合理地移植.

在这种情况下,“缓存”通常是指在硬件级别上进行的活动. java中存在某些事件导致多处理器系统上的核心“同步”其缓存.访问volatile变量就是一个例子,synchronized块是另一个.想象一下这两个线程X和Y被安排在不同处理器上运行的场景.

X starts and is scheduled on proc 1

y starts and is scheduled on proc 2

.. now you have two threads executing simultaneously

to speed things up the processors check local caches

before going to main memory because its expensive.

x calls setSomeValue('x-value') //assuming proc 1's cache is empty the cache is set

//this value is dropped on the bus to be flushed

//to main memory

//now all get's will retrieve from cache instead

//of engaging the memory bus to go to main memory

y calls setSomeValue('y-value') //same thing happens for proc 2

//Now in this situation depending on to order in which things are scheduled and

//what thread you are calling from calls to getSomeValue() may return 'x-value' or

//'y-value. The results are completely unpredictable.

关键是volatile(在兼容的实现上)确保有序写入将始终刷新到主存储器,并且在下次访问之前,其他处理器的高速缓存将被标记为“脏”,而不管发生该访问的线程.

免责声明:volatile不会锁定.这在以下情况下尤为重要:

volatile int counter;

public incrementSomeValue(){

counter++; // Bad thread juju - this is at least three instructions

// read - increment - write

// there is no guarantee that this operation is atomic

}

如果您的意图是必须始终在getSomeValue之前调用setSomeValue,这可能与您的问题相关

如果意图是getSomeValue()必须始终反映最近对setSomeValue()的调用,那么这是使用volatile关键字的好地方.请记住,如果没有它,即使首先调度了setSomeValue(),也无法保证getSomeValue()将反映最近对setSomeValue()的调用.

你可能感兴趣的:(java多线程缓存)