user291701
user291701

Reputation: 39671

Memcache or just a static instance per app instance?

I have a somewhat complex object in my web app, it would take some time to make all its attributes serializable so I could stick it in memcache.

Is there any sense to just keeping it around as a static variable in my web app? I'm not sure how static variables work in app engine. I was thinking of something like this:

public class MyServlet {
    private static SpaceShuttle mShuttle;

    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws IOException 
    { 
        // If the static instance isn't already around in this
        // application instance, build it.
        if (mShuttle == null) {
            // Create it once.
            mShuttle = complexProcessOfCreatingASpaceShuttle();
        }

        // Use it.
        mShuttle.liftOff();
        ...
    }   
}

I think memcache would be helpful here since different application instances could share the same object (I think?), but as a temporary fix, at least app instances could share the static instance for the lifetime.

The SpaceShuttle is immutable / read-only so there's no synchronization danger (I think?).

Lots of unknowns here, not sure how app engine works internally. Should I just try making the entire SpaceShuttle serializable?

Thanks

Upvotes: 1

Views: 649

Answers (2)

Peter Recore
Peter Recore

Reputation: 14187

This depends on whether the SpaceShuttle object needs to share state between instances. When running on app engine, your app can have between 0 and many instances running at any given time. Each instance will look like its own JVM. (Each instance/JVM might also have multiple threads running within it.) So as long as your object doesn't need to share state with other instances, you should be fine, and by keeping it around you would be saving your app from having to initialize it for every request.

If your space shuttle objects all need to be synchronized with each other (because they represent some global application state) then you will need some mechanism to keep them in sync, which might be just as annoying as trying to put them in memcache to begin with.

That being said, maybe you can put some of the space shuttle into memcache. Perhaps you can memcache parts of it, and then grab those when doing the instance specific initialization?

Upvotes: 3

Mike Axiak
Mike Axiak

Reputation: 11994

No. This is an issue I see all too often especially on Java web applications -- using persistent static variables are impossible to scale. If it's difficult to serialize the entirety of the SpaceShuttle object, perhaps you can break the problem up and serialize pieces of it?

Upvotes: -1

Related Questions