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...
Asked
Active
Viewed 51 times
-2
-
3You can never trust a test to tell you that something _isn't_ thread safe. Thread safety bugs don't always happen; they only happen at the worst possible time when they're least debuggable. – Louis Wasserman Jun 29 '22 at 04:53
-
2It seems likely that what you have is not thread safe. However the right way to be sure would be to post the code and let us look at it. – markspace Jun 29 '22 at 04:55
-
1This is *not* thread-safe. All methods that change the data structure must synchronize on the same object. Your test proves nothing. You have to establish thread-safety analytically. – user207421 Jun 29 '22 at 04:56
-
There is a race condition in your code, if you want to avoid that, you have to mark the delete method synchorized as well or you can use CopyOnWriteArrayList or you can use Collections.synchronizedList(). Read More here for detail https://stackoverflow.com/questions/6916385/is-there-a-concurrent-list-in-javas-jdk – mksmanjit Jun 29 '22 at 04:57
1 Answers
0
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 e.g 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 (e.g. 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.

pveentjer
- 10,545
- 3
- 23
- 40