views:

38

answers:

2

I have a GWT+GAE web app with several service and modules. I am using the module functionlity of mvp4g. All of my services extends:

public abstract class BaseServiceImpl extends RemoteServiceServlet {
 protected final static Map USERS = new HashMap();

I use USERS to store my current active user sessions. Once I user authenticates himself I store his session id as a key of the map.

protected String getSessionId() {
    return getThreadLocalRequest().getSession().getId();
}

public String authenticate(String username, String password) {
    ...
    ..
    .
   String id = getSessionId();
   synchronized( this ) {    
       users.put(id, user);
   } 
   ...
   ..
   .

For every request, I check if the user session is still valid.

protected boolean validUserSession() {  
    if(getThreadLocalRequest() == null) {
     logger.log(Level.SEVERE, "Thread is null");
     return false;
 } else if(getThreadLocalRequest().getSession() == null) {
     logger.log(Level.SEVERE, "Session is null");
     return false;
 }
 String id = getSessionId();
 UserJDO user = (UserJDO) users.get(id);
 if(user==null) {   
     logger.log(Level.SEVERE, "User is null");
     return false;
 }
 return true;
}

I have sessions enabled. Next I post the last lines of appengine-web.xml

...
..
.
<sessions-enabled>true</sessions-enabled>
</appengine-web-app>

Everything works fine in the Development server. However, when I deploy it to the google app engine cloud the users variable is reset for every request.

Can anyone explain me what it is happening? How should I proceed? Should I store the user sessions in the datastore?

+5  A: 

In GAE, each request may hit different server. Furthermore, your application might be undeployed and redeployed again before each request. You should not rely on static variables. Save your state in sessions or in database.

Here is quote from http://code.google.com/appengine/docs/java/runtime.html

App Engine uses multiple web servers to run your application, and automatically adjusts the number of servers it is using to handle requests reliably. A given request may be routed to any server, and it may not be the same server that handled a previous request from the same user.

Once you enable sessions, they are automatically stored to datastore at the end of requests.

Peter Štibraný
+2  A: 

Google App Engine may run every request on a different server. They make no guarantees about request being served by the same instance of the VM on the same machine. You will need to store your user information in a persistent store, such as a BigTable table.

Greg Hewgill