Safely Handling Concurrent Memcache Updates in AppEngine

懵懂的女人 提交于 2019-12-22 08:59:24

问题


The Google Apps Engine doc about safely Handling Concurrent Memcache Updates:

The putIfUntouched and getIdentifiable methods of the Memcache service can be used to provide a way to safely make key-value updates to memcache in scenarios where multiple requests are being handled concurrently that need to update the same memcache key in an atomic fashion. (It is possible to get race conditions in those scenarios.)

i am building an application which need accurate cache value, below is my code, please help me check if it is right:

        ...
        IdentifiableValue oldCountIdValue = mc.getIdentifiable( cacheKey );
        Long count = ( Long ) oldCountIdValue.getValue();
        if( count != null )
        {
            this.oldCountValue = oldCountIdValue;
            return count;
        }

        Long result = new Long( q.count() );
        mc.putIfUntouched( cacheKey, oldCountValue, result );
        return result;

My question is: what if putIfuntouched() return false? what should the code return? and how?

When the datastore add one entity, i use below:

mc.increment( cacheKey, 1, initValue );

is this usage correct?

Thanks a lot.


回答1:


I need to understand something about your code:
First why are you checking if count != null? doesn't oldCountIdValue == null means that count == null and the other way around: if oldCountIdValue != null then count != null

if so then the code should be:

IdentifiableValue oldCountIdValue = mc.getIdentifiable( cacheKey );
if (oldCountIdValue != null) {
   return ( Long ) oldCountIdValue.getValue();
}

Long result = new Long( q.count() );
mc.putIfUntouched( cacheKey, oldCountValue, result );
return result;

if putIfUntouched returns null, it means that your result variable is not accurate anymore, you can do the following: ignore and return your current result or load the result from the cache.



来源:https://stackoverflow.com/questions/10501852/safely-handling-concurrent-memcache-updates-in-appengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!