This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
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:
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.)