How long will a thread wait for a race condition in the following scenario?
A file is added to a collection:
lock(mylock) { // add to collection }
It is then removed from the collection in a similiar manner.
If a thread is trying to add to the collection while the service is removing it from the collection, who wins?
Or is that the point of a race condition, you can’t predict who wins?
If the removing thread tries to lock first, it owns the lock, removes the item (if it exists), releases the lock, and moves on. Then the adding thread grabs the lock and adds the item. End result: item exists in the collection.
If the adding thread tries to lock first, it owns the lock, adds the item, releases the lock, and moves on. Then the removing thread grabs the lock and removes the (just-added) item. End result: item does not exist in the collection.
Neither thread will wait for longer than is necessary to add or remove an item from the collection.