简体   繁体   English

非同步方法可以与同步方法交错吗?

[英]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.

相关问题 我可以调用一个同步方法,该方法调用一个调用同步方法的非同步方法吗? - Can I call a synchronized method that calls a non-synchronized method that calls a synchronized method? 是否可以将非同步方法称为已同步? - Is it possible to call a non-synchronized method as synchronized? Java同步方法...未同步 - Java Synchronized method…not synchronized Java同步方法未同步 - Java synchronized method is not synchronized 实例的同步方法可以被同步语句锁定吗 - Can a synchronized method of an instance be locked by synchronized statement java:可以同步块交错吗? - java: can synchronized block interleave? 如果我从我的synchronized方法调用非同步方法是非同步方法线程安全吗? - if i call a non synchronized method from my synchronized method is non synchronized method thread safe? 如果一个同步方法调用另一个非同步方法,非同步方法是否有锁 - If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method 令人困惑的Java同步方法,synced(this)和synced类 - Confusing Java synchronized method, synchronized(this), and synchronized class 同步语句 - 同步方法和同步语句等效吗? - Synchronized statements - are synchronized method and synchronized statements equivalent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM