views:

55

answers:

3

I read that in Google App Engine there is a chance that a singleton class might die, if the application gets idled for too long (or a new application instance is created), and I have experienced this myself.

But does that really mean that Any static variable in any class might get expired in the application? or how can GAE identify that this class is a singleton?

+1  A: 

Someone correct me if I'm wrong on this, but I think you can't have singletons at all, as your app can run in n processes.

hackbert
That's true, and the app can also be loaded in multiple classloaders inside the same process. However, the typical case is that there is just one instance of the app, and so one instance of any singletons. (Since your post isn't really an answer, but more of an aside, it would have been best posted as a comment under the question.)
mdma
@mdma: It isn't an aside, as it answers the question: There is no singleton possible if you can't be sure it's a singleton. And even if it should be a comment: I can't comment the posts of other users ;D
hackbert
+1  A: 

Assuming the singleton is implemented as static methods in a class, or as a static reference (are there other ways?), the singleton can be garbage collected by unloading the classloader that loaded the singleton class, assuming that there are no references from classes in other class loaders (e.g. a common problem is ThreadLocal instances hanging on to references.)

I haven't used GAE, but my guess is that this is what is happening - the classloader is being unloaded. GAE doesn't know this is a singleton - it simply frees the reference to the class loader. For applications in a container, this is ideally the only reference keeping the app in memory (if you are lucky!). Once this is non-reachable, the entire app becomes non reachable and is collected by the garbage collector. Of course, any threads running may have references to app instances, and so will interfere with this, but I'm assuming the container has control over the apps threads and only frees the classloader when there are no requests (i.e. threads) running the app's code.

mdma
+2  A: 

App Engine can and will unload applications that are idle for a long undefined period of time. In other words, you application will essentially be shut down.

In addition, GAE may run your application in many processes across many servers if your traffic is high enough.

So really, relying on static members or even Singletons is probably a bad idea in such an environment - with GAE you are not in control of when your application is started/stopped/loaded on other machines.

These two questions in the GAE Java FAQs partially address this:

edit: I should say that "long period of time" is actually undefined, and I don't think Google publishes it. It would be more correct to say App Engine will unload applications that are idle for some undefined period of time.

matt b