What is the proper scope for App Engine services when creating a servlet: static, instance, or local? And what are the implications of each? It seems like you should want to use them in as wide a scope as possible, to avoid the overhead of re-creating (or re-retrieving) them, but I wonder as to whether this will cause improper reuse of data, especially if <threadsafe>true</threadsafe>.
Examples of each scope are provided below. MemcacheService will be used in the examples below, but my question applies to any and all services (though I’m not sure if the answer depends on the service being used). I commonly use MemcacheService, DatastoreService, PersistenceManager, ChannelService, and UserService.
Static scope:
public class MyServlet extends HttpServlet {
private static MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
memcacheService.get("x");
}
}
Instance member:
public class MyServlet extends HttpServlet {
private MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
memcacheService.get("x");
}
}
Local scope:
public class MyServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
memcacheService.get("x");
}
}
GAE is a distributed system where all of it’s services run on separate servers. So when you invoke a service it internally serializes the request (afaik with protocol buffers) sends it to the server running the service, retrieves the result and deserializes it.
So all of
*Serviceclasses are basically pretty thin wrappers around serialization/deserialization code. See for example source of MemcacheService.About scope: there is no need to optimize on
*Serviceclasses as they are pretty thin wrappers and creating them should take negligible time compared to whole service roundtrip.