1

I have a servlet which accesses and modifies an object "myBean" stored in a servlet context. Is explicitly locking "myBean" with a synchronized block needed or it is maintained by default? Example code:

   public class StopFilesMergeServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
            MYBean myBean = req.getServletContext().getAttribute("myBean");
            synchronized (myBean) { //is this necessary?
                int oldValue = myBean.getProperty1();
                int newValue = oldValue + 10;
                myBean.setProperty1(newValue);
            }
            ...
            return;
    }
Yaros
  • 75
  • 8
  • I would recommend making the bean itself thread-safe, with higher-level operations that can be called normally from any thread, rather than depending on people remembering that this or that thing needs to be synchronised externally. And please also watch out for [TOCTTOU](https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use) problems. – biziclop Aug 06 '17 at 16:15
  • According answers make bean thread-safe is the best solution. But what about HashMap or other collection I also store in ServletContext? – Yaros Aug 06 '17 at 17:27
  • Wrap them in thread-safe containers too. But if you find yourself storing lots of mutable data in the servlet context (which of course is shared across all the sessions), that also raises the suspicion that your real problem is the architecture. – biziclop Aug 06 '17 at 17:31
  • Also same question exactly about HashMap: [Thread Safety of ServletContext objects](https://stackoverflow.com/questions/20190070/thread-safety-of-servletcontext-objects). Answerers state to use java.util.concurrent.ConcurrentHashMap – Yaros Aug 07 '17 at 03:06

1 Answers1

0

Spring does NOT do anything under the hood to guarantee thread-safety for beans.

Is explicit locking "myBean" with syncronized block needed or it is mainteined by default?

Your intention is not clear from your example. You need explicit locking if you are reading value from the a bean, comparing it and then updating. A better option would be make myBean thread-safe itself if it has state.

goblinjuice
  • 3,184
  • 24
  • 26