[英]Can a non synchronized method interleave with a synchronized method?
When I have a class with a List and two methods operating on that list.当我有一个带有 List 的类和在该列表上运行的两个方法时。 A synchronized one that adds an element and later works on that element.
一个同步的,它添加一个元素,然后在该元素上工作。 And a non synchronized method that deletes elements in that list, could that lead to a race condition in a multi-threaded situation?
以及删除该列表中元素的非同步方法,这会导致多线程情况下的竞争条件吗? I would have thought so, but I tested it (with vmlens) and that test suggests, there will be no problem.
我本来是这么想的,但是我测试了它(使用 vmlens)并且测试表明,不会有问题。 Maybe I didn't fully understand "synchronized" yet...
也许我还没有完全理解“同步”......
Your code is suffering from 2 types of problems:您的代码存在两种类型的问题:
race condition比赛条件
data race数据竞赛
The race condition could happen when the add and delete are both updating the list and it could lead to eg the size of the list becoming inconsistent with the actual number of items due to an unlucky scheduling of requests.当添加和删除都在更新列表时,可能会发生争用情况,并且它可能导致例如由于请求调度不吉利而导致列表的大小与实际项目数不一致。
Because you don't have any synchronization (eg synchronized or volatile) there are no happens-before edges between writing and reading the list.因为您没有任何同步(例如同步或易失性),所以在写入和读取列表之间没有发生之前的边缘。 And this can lead to all kinds of problems like reordering, and visibility (and atomicity) problems.
这可能导致各种问题,例如重新排序和可见性(和原子性)问题。 For more information about data races, it is best to dig into the Java Memory Model .
有关数据竞争的更多信息,最好深入研究Java 内存模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.