Search code examples
javajspservletsparse-platformservletcontextlistener

Should this class be in the ServletContext or session scoped in a JSP web applicaiton?


I am working on a JSP web app to use HttpURLConnection to receive and transfer data from/to a Parse.com database via their REST services. The web application will need to be deployed on Google App Engine or Amazon Web Services.

I have defined a ParseUtils class that is responsible for getting or posting data from or to the Parse database tables through HttpURLConnection class. It has many functions in it and each function establishes a HttpURLConnection for a particular Parse table.

Hope I have given out as many details as needed. My question is: should the ParseUtils class be declared and initialized in the ServletContext when the ServletContext gets initialized or be defined as a session-scoped object for each session? Any best practice?

Thanks!


Solution

  • Connection objects are typically not "shareable" in the concurrent access sense of the word (they are reusable however, in that turn-based access is permissible in a managed environment/execution context). Given that HttpURLConnection is not threadsafe, there's no reason to keep it in a global, shared-state component like the ServletContext.

    That leaves you with the request and session scopes, and also a need to answer the following questions

    1. What's the overhead associated with establishing a new HttpURLConnection for each request?
    2. What's the likelihood/need that a single connected client would need to open two pipes, i.e. two HttpURLConnections in a single session either by way of a new window or tab

    The answer to #1 is the overhead is there, but very slight; if there's even a slight chance of #2 being a possiblity, you definitely want to open a new HttpURLConnection per request, or better yet consider springing for Apache's HttpClient to take advantage of stuff like connection pooling