1

We have a Java servlet acting as dispatcher for a web app. For each request a database connection is created and then committed / rolled back at the end of the request depending on whether the action was successful or not. It looks something like:

public class WebDispatcher extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws ServletException, IOException {

        Connection conn = null;

        try {

           // Create connection

        } catch(.....) { 

        } finally {

          // Commit / Rollback connection

        }

    }

}

The problem occurs when there is an exception. For example if they don't have access to a certain action the dispatcher has to redirect them. It does this by using a request dispatcher.

} catch(RoleAuthorizationException rae) {

    request.getRequestDispatcher(.....).forward(request, response);

}

I had assumed that 'finally' would be called but it doesn't seem to be in this case. With each exception we end up losing a connection in the pool. As a workaround we are closing the connection with each exception but why isn't finally being called?

esen
  • 65
  • 5
  • Perhaps some of these answers and comments will give you an idea? [here](http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java) – Rick S Feb 18 '15 at 19:55
  • 1
    i am guessing your example code is not representative. esp since "closing the connection with each exception" works. i think your connection is held by an instance variable or threadlocal, and it gets overwritten when the forwarded request gets processed, leaving the original connection hanging out to dry. – Nathan Hughes Feb 18 '15 at 20:01
  • I think you're absolutely right, just didn't see it. The connection is put into the request and passed into the next action which is usually a call to the dispatcher again. The dispatcher never bothers to check and see if there is already a connection in the request and creates a new one overriding the existing connection and leaving it as you said hanging out to dry. – esen Feb 18 '15 at 20:09

1 Answers1

1

Finally is always called (oracle docs):

The finally block always executes when the try block exits.

Check if there is an exception being thrown in the finally block (before the connection is closed).

See also this answer.

Community
  • 1
  • 1
mk.
  • 11,360
  • 6
  • 40
  • 54