简体   繁体   中英

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. 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM