Announcement Announcement Module
Collapse
No announcement yet.
threadsafe controllers? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • threadsafe controllers?

    I have an interceptor that "injects" an object instance into a controller:

    Code:
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
        StatusMsgManager smm = (StatusMsgManager) request.getSession().getAttribute(ServletConstants.ATTR_STATUSMSG_MANAGER); 
        
        // put status msg manager in http session if not already
        if(smm == null) {
          smm = new StatusMsgManager();
          request.getSession().setAttribute(ServletConstants.ATTR_STATUSMSG_MANAGER, smm);
          log.info("put new StatusMsgManager instance into http session");
        }
        
        // inject it into the handler if called for
        if(handler instanceof StatusMsgPoster) {
          ((StatusMsgPoster)handler).setStatusMsgManager(smm);
        }
        
        return true;
      }
    The handler then uses the injected instance when handling requests:

    Code:
      /*
       * StatusMsgPoster implementation
       */
      public void setStatusMsgManager(StatusMsgManager statusMsgManager) {
        this.statusMsgManager = statusMsgManager;
      }
    
      public void postStatusMsg(String msg, MsgLevelEnum level) {
        statusMsgManager.postStatusMsg(msg, level);
      }
      ///
    Do I need to worry about threadsafety? Currently my controllers are all singleton model. Should they be prototypes? Or should I abandon this approach all together.

    Thanks for any wisdom.

    Jon

  • #2
    Yes, because they are singletons, they will have multiple threads accessing them.

    Short term, make them prototypes.

    Long term, there is some code in the sandbox that can do pretty much what you are looking to do, but it's definitely not ready. Your controllers will still need to be prototypes, but the injection from "stateful" beans can happen automatically. Look in the org.springframework.aop.target.scope package in the sandbox.

    Seth

    Comment


    • #3
      Sounds good. Thank you!

      Comment


      • #4
        Why not just retrieve the StatusManager from the session directly in the controller? You could still hide it behind a factory type thing, i.e.:

        Code:
          interface StatusManagerFactory {
            StatusManager getStatusManager(final HttpServletRequest request);
          }
        and pass that into the controller. Whenever you need the SM call statusManagerFactory.getStatusManager(request).

        Just an idea....

        Can you not make StatusManager threadsafe?

        Comment


        • #5
          Yes. This is what I am doing now.

          Comment

          Working...
          X