Skip to content

Instantly share code, notes, and snippets.

@qsLI
Forked from raskasa/ServletThreadSafety.java
Created August 11, 2016 09:32
Show Gist options
  • Save qsLI/f386c48b798654f866bbfb16c29ec345 to your computer and use it in GitHub Desktop.
Save qsLI/f386c48b798654f866bbfb16c29ec345 to your computer and use it in GitHub Desktop.
An example of how to deal with concurrency and thread-safety when accessing context and session attributes. Context attributes can be accessed by an part of the web app including Servlets, JSPs, ContextListeners, and ServletContextAttributeListeners. Session attributes are only for one client, but opening up another new browser windows on the sa…
public class ServletThreadSafety extends HttpServlet {
/*
* Since we have the context lock, we're assuming that once we get inside the synzchonized block,
* the context attributes are safe from other threads until we exit the block... soft of. Safe
* means "safe from any other code that ALSO synchonizes on the ServletContext".
*
* But this is the best you've got for making the context attributes as thread-safe as you can.
*/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println("test context attributes<br>");
/*
* Now we're getting the lock on the context itself. This is the way to protect context
* and session attribute state. (You don't want synchonized(this).) In general, you
* must synchronize the part of your code that accesses context and/or session attributes.
*/
synchronized(this.getServletContext()) {// For session attributes, do: synchronized(req.getSession()) {...}
this.getServletContext().setAttribute("foo", "22");
this.getServletContext().setAttribute("bar", "42");
writer.println(this.getServletContext().getAttribute("foo"));
writer.println(this.getServletContext().getAttribute("bar"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment