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

  • threadsafe controllers?

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

      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);
"put new StatusMsgManager instance into http session");
        // inject it into the handler if called for
        if(handler instanceof StatusMsgPoster) {
        return true;
    The handler then uses the injected instance when handling requests:

       * 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.


  • #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 package in the sandbox.



    • #3
      Sounds good. Thank you!


      • #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.:

          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?


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