Java servlet doGet() method declares a hashmap inside the method. Does it need to be synchronized for thread safety for multiple requests? What is the scope of a locally declared object using new within a method?
Asked
Active
Viewed 306 times
1 Answers
4
If you're talking about local variables: no, synchronization is not needed.
A single method in a servlet may be executed by multiple threads simultaneously, but variables declared in that method are not shared. Each invocation of a method has its own copy of local variables.

Matt Ball
- 354,903
- 100
- 647
- 710
-
Thanks Matt Ball. So what happens if a HashMap m = new HashMap() is created from within the method to do something. Will it require synchronization? – user2529898 Jun 27 '13 at 22:28
-
I can't answer that without a better explanation of how it's shared, passed around, etc. Are we still talking about a **local** variable? Does the code expose this object to multiple threads? – Matt Ball Jun 27 '13 at 22:41
-
Apologies... for simplification, lets assume that the hashmap is created within the method, and used within the method only. Would it(the declared hashmap variable 'm') have to be synchronized in that case? – user2529898 Jun 27 '13 at 23:33
-
No. That's exactly the case I talked about in my answer. Each method invocation's local variables are specific to that method call. That's the definition of a local variable. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html – Matt Ball Jun 27 '13 at 23:37
-
Ok, thanks. So I believe if its used somewhere within the class, or outside of the class, to ensure thread-safety its best to synchronize it. Moreover, if declared locally, will the hashmap be available on the thread stack frame or will it be created on the heap? – user2529898 Jun 27 '13 at 23:42
-
To ensure thread safety, you could avoid synchronization if you know that only one thread will use the map at at time. Regarding storage location, there are plenty of existing things to read on SO and elsewhere. I suggest you take some time to research for yourself. Here are a few to start you off: http://stackoverflow.com/q/2099695/139010, http://stackoverflow.com/q/873792/139010, http://stackoverflow.com/a/3646660/139010, http://stackoverflow.com/q/17312443/139010, and so on. – Matt Ball Jun 27 '13 at 23:47