If you're pretty sure the friend is not on the list, then locking the file exclusive for the entire operation is a good idea.
However, locking the file in LOCK_EX (instead of LOCK_SH) will limit the concurrency of the operation to 1. So if you just want to check if they are (not) on the list, a shared lock will scale better. Check again after you get an exclusive lock, to avoid race conditions. (For even better scalability, use a database.) | [reply] |
OPTIMIST (likely to find the item in the list): Start with a shared lock, and without unlocking, "promote" to an exclusive lock once not found; make sure there is a timer on the attempt to prevent a deadlock, and if the timer goes off then unlock and retry from the top.
PESSIMIST (unlikely to find the item in the list): Use the exclusive lock from the beginning.
| [reply] |
Thank you for your comment!!! I saw this bug also! but wasn't sure if it's a bug. read/write from the very beginning must be a good solution if it works, I haven't tried that out | [reply] |