Created
December 18, 2012 20:27
-
-
Save raskasa/4331644 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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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