Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

Thread safe

Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
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.
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 ]
So I left, I came home, and I ate some pie. And then I read this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
    Bookmark Topic Watch Topic
  • New Topic