This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes thread safe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "thread safe" Watch "thread safe" New topic
Author

thread safe

Raj Neets
Ranch Hand

Joined: Nov 12, 2002
Posts: 46
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

Joined: May 29, 2003
Posts: 1258
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.)


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
Raj Neets
Ranch Hand

Joined: Nov 12, 2002
Posts: 46
Thanx got it
raj
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread safe
 
Similar Threads
Mock Question
Thread safe Please help!!!
Thread safe
Threads and local variables
question from the jweb+