views:

60

answers:

3

When I launch my site in hosted mode all variables that are declared as static preserves it's values among different requests. It works fine(?) when I upload it to google app servers.

I.e. I have public static String action = "index"; and if I set its value to "someval" in another request it appears "someval" instead of "index".

Is it supposed to be so? Where could I search for this problem solution?

A: 

Using public static final String action = "index"; will ensure action's value doesnt change.

Zaki
What If I need to change it?
Tadas D.
A: 

Yoi should consider using The Memcache API.

See also Google App Engine: Memcache or Static variable?.

stacker
I don't need any kind of caching. I am just trying to normally use static variables as I want. The main "problem" as it seems, that webapp isn't terminated after it's request is completed...
Tadas D.
You should at least go through the second link to learn why this happens.
stacker
+1  A: 

Instances of your app are kept around in memory for multiple requests, for efficiency. If an instance doesn't process any requests for a while, it gets shut down. So yes, you will see this behaviour, where changing a global in one request affects it in another. More importantly, the Java Servlet spec permits multiple threads of execution, so another request could be executing and modifying your globals at the same time as another request is.

In production, your app may be running simultaneously on many servers. Naturally, these don't have the same set of global variables, so changing the value in one will only affect subsequent requests to the same handler - not requests to other handlers.

In short, mutable globals in a webapp are generally a Bad Idea.

Nick Johnson
So what about Singleton pattern usage in such case?
Tadas D.
If you're instantiating something read-only, or you're caching something optimistically in local memory, fine. Anything else, and you should be using memcache or another globally consistent store such as the datastore.
Nick Johnson
Em... Is there any in-depth article about such behavior (variables and lifespan of java webapp). I have PHP background so this is quite a surprise for me...
Tadas D.
I'm not sure there's anything else to say: One instance can serve any number of requests; there can be multiple running instances; plan accordingly. In general, using mutable statics at all in Java is a bad idea, because it's multi-threaded.
Nick Johnson