سؤال

Image my server provides an email service that I am using memcache for. When a sender sends a new email to user X, the key for X is removed from the cache. When user X makes a call to getInbox the response is added to the cache under the key for X (so that the same response is returned for subsequent calls to getInbox until a sender removes the key and the process continues). So a very simple design. But what happens when X is reading at the same time that some sender is sending X an email? Per my understanding putIfUntouched and getIdentifiable do not help here. As they seem to only work if I am using in putIfUntouched the exact same instance/value returned by getIdentifiable, which is not possible in my case since I am talking about two different service calls. So does anyone know how I might avoid race conditions in my simple model?

update

In light of @AndreiVolgin's response, let me add details to what I perceive to be the race condition:

Sender's job is to remove the key; recipient's job is to 1) read the value with syncCache.get(key), 2) if the value is null then set the key to a real value with syncCache.put(key, value). The problem is in the case where send is trying to set the value to null while at the same time recipient is calling syncCache.put(key, value). If recipient wins in setting to value then recipient may never get to see the change made by sender.

هل كانت مفيدة؟

المحلول

This is not a race condition. A user will simply not see a message sent to him a few milliseconds before he checked his Inbox.

There is no way to avoid that, and there is no reason to avoid that. What if a message is delivered 1 ms after your Memcache call as opposed to 1 ms before this Memcache call? Won't a user be equally upset?

UPDATE:

Based on OP comments, one process sets a flag (no new massages) using a memcache, while another process removes it when a new message arrives. If a new message fails to remove the flag because it coincided with a user setting a flag, a new message will be invisible until the next message arrives.

While extremely rare, this is a valid concern. The solution, in my opinion, is to set an expiration time on flags as a fail-safe for this rare condition.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top