Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread safe

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
In the below code:
import java.util.*;
public class TestServlet extends HttpServlet
{
static HashMap staticMap = new HashMap();
HashMap theMap = new HashMap();
public void init()
{
}
public void service(HttpServletRequest req, HttpServletResponse res)
{
super();
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
HashMap localMap = new HashMap();
//do something
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
HashMap sessionMap = (HashMap) req.getSession().getAttribute("map");
//do something
}
}
I believe that the request attributes and LOCAL OBJECTS are thread safe but sessionMap is not thread safe. Why??
Thank you in advance.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, what is a "local object"? A local object is not an object reference held in a local variable, but an object which is only locally reachable.
The object referred to by the sessionMap variable is session-scoped, i.e. bound as an HttpSession attribute. This makes it non-locally reachable. Because a single session may easily experience multiple simultaneous requests -- each of which probably gets its own thread -- the object is (in principle) not safe against multi-threaded access.
Multiple concurrent requests for the same session are a common occurrence with frames, dynamically rendered graphics or other embedded/included page elements, users with no patience for servers under load, etc.
- Peter
[ April 13, 2002: Message edited by: Peter den Haan ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic