Joel Blum
Joel Blum

Reputation: 7878

Referring to Memcache Objects And Updating them

This is a very general question regarding GAE / Java Memcache :

I have an object called Network which is stored in the Memcache , and I have another object called User which has a reference to Network .

Network network=Memcache.get(networkKey);
user._network=network;    //user references an object that came from Memcache...

now I have a bunch of code that changes user._network(without touching Memcache) :

user._network= // do some changes to the objects , without touching Memcache

Ok so here's the question , Looking at the code as it is , did the last line update the network object in the memcache? I have servlets that need to access the updated network object , the question is if I'm wrong by thinking at Memcache objects as regular objects .

Perhaps the right way is this ?

Network network=Memcache.get(networkKey);
network.doUpdate();
Memcache.put(key,network);

Upvotes: 2

Views: 784

Answers (2)

Rick Mangi
Rick Mangi

Reputation: 3769

The code does update the Network object in memcache but references to the object in other parts of your application that already have a handle on that Network instance are not updated. Memcache stores SERIALIZED objects.

The best way to use memcache in GAE is in conjunction with something like Objectify for caching datastore objects and for storing large collections of objects that are expensive to generate. It's not well suited to storing objects that change frequently or that are used by many other objects in your application.

Upvotes: 0

Dan Holevoet
Dan Holevoet

Reputation: 9183

The latter code example you provided is the correct way to update the network object in memcache, but I it will work differently than the way you expect.

Your user object refers to an instance of the network object that has been retrieved from memcache. Each time you retrieve the object from memcache you will get a different instance. And, because the instances are logically distinct from the original within the cache, as soon as the cached value is updated, those instances will become out of sync with the cached version.

For example:

Network network=Memcache.get(networkKey);
Network networkTwo = Memcache.get(networkKey);
user._network=network;
networkTwo.doUpdate();
// network and networkTwo are now different
Memcache.put(networkKey,networkTwo);
// user._network still refers to the initial instance of network, not networkTwo

You'll need additional logic in your code if you want your User objects to always refer to the version of network that is in memcache.

Upvotes: 4

Related Questions