This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread safe

 
Raj Neets
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was taking a practice test, I came across the following question, in that ( HashMap localMap = new HashMap() decleared in doGet())correct answer was only localMap object is thread safe but other (hashmap)objects are not thread safe. can some please explain to why only localmap object is threads, my understanding was it is also not thread safe.
Consider the following code for a servlet:

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
}
}
//[code]
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, the web container is going to use a single Servlet instance to handle multiple requests. That means that multiple threads will be accessing static and instance members. These objects MUST be synchronized in order to be thread-safe.
Objects that are declared/instantiated within methods are what we call "automatic" or "stack" variables. They are only accessible to the thread that is executing that method. In your example, localmap is declared and created within a method, and so is only accessible to the thread that is executing that block at that point. Therefore, it is thread-safe.
(Technically, if a thread declares/instantiates an object in a method, but sets a static or instance variable to refer to it, it would cease to be thread-safe, but just don't do that.)
 
Raj Neets
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx got it
raj
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic