简体   繁体   中英

Safely Handling Concurrent Memcache Updates in AppEngine

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM