• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

thread safe

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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]
 
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanx got it
raj
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic