何时对同步块的更改对其他线程可见 [英] When are changes in Synchronized block visible to other threads

查看:120
本文介绍了何时对同步块的更改对其他线程可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在同步方法中更新了两个变量的值。在退出synchronized块之前,其他线程可以看到同步方法中设置的新值是否可见?

Say that I update values of two variables in a synchronized method. Would it be possible that the new values set in synchronized method be visible to other threads before exiting the synchronized block?

public synchronized void setValues(){
    a=5;
    // assume thread is preempted after this assignment
    // would the value 5 be visible to other threads?
    // my understanding is that the values will not be flushed to
    // main memory until the lock is released- i.e., until the synchronized
    // method is complete. So the changes will not be visible to other 
    // threads even when not using synchronization
    b=10;
}

以下方法同步,所以我理解线程可能看到陈旧的值。我的问题是如果线程在分配给a后被抢占,是否有可能在printValues方法中可见变量a的新值5?

Below method is not synchronized, so I understand that the thread may see stale values. My question is if the thread is preempted after assignment to a, is it ever possible that the new value "5" for variable a be visible in printValues method?

public void printValues() {
    System.out.println(a + " " + b);
}


推荐答案

是,在同步中进行的更改在到达synchronized块的末尾之前,可以(但不保证)可见。基本上,在阅读写入数据时,您通常需要同步(在同一个锁上)以获得一致的世界视图。

Yes, changes made within synchronized can (but aren't guaranteed) to be visible before you get to the end of the synchronized block. Basically, you usually need to synchronize (on the same lock) when reading or writing data in order to get a consistent view of the world.

为同步提供的保证是使做正确的事(正确同步)正常工作 - 他们保证当你不做正确的事情(观察共享变量而不进行同步)。

The guarantees provided for synchronization are to make "doing the right thing" (synchronizing appropriately) work correctly - they don't guarantee that changes are made atomically when you're not doing the right thing (observing the shared variables without synchronizing).

您可以(在某种程度上)将同步块内的写入视为对<的调用code> OutputStream.write(),同步块的退出就像 flush()调用一样。当你走过街区的一半时,你写的可能的一些数据已经输出到输出文件(或者其他) - 但它仍然可以被缓冲。这并不意味着表明内存模型是如何实现的,只是为了帮助您了解如何保证可见性的类比。

You can (to some extent) think of the writes within the synchronized block as being like calls to OutputStream.write() with the exit of the synchronized block being like a flush() call. When you're half way through the block, some of the data you've written may have made it to the output file (or whatever) - but it might still be buffered. That's not meant to be an indication of how the memory model is implemented, just an analogy to help you understand how the visibility isn't guaranteed.

这篇关于何时对同步块的更改对其他线程可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆