Friday, 9 July 2010

Concurrency problems in jsp Pages

I'm so ashamed that I didn't notice this problem sooner, but apparently servlets (and, therefore, jsp pages too) are instanced and put into a pool for multithreaded use.

This has the very bad effect of messing with your class variables.

So, do NOT do the following:

// authentication && authorization

/* name of the current user logged in */
private String itsPlayerName;

private Logger itsLog = Logger.getLogger("mmud");
/* password of the current user logged in, unsure if used */
private String itsPlayerPassword = "";
/* sessionid/cookiepassword of current user */
private String itsPlayerSessionId;

private StringBuffer contents = new StringBuffer("");

A JSP page is by default thread unsafe. This means that multiple requests, started in multiple threads for a specific JSP access the same Instance.

Do not make your JSP page threadSafe="true". It will become a performance nightmare.

If you are interested, the following is put in the javadoc of the javax.servlet.Servlet interface service method:

Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet's class and instance variables.

No comments:

Post a Comment