javaobjectservletsinstantiationapache-commons-dbutils

DBUtils QueryRunner instantiation


I have a webservice that instantiates a single QueryRunner with a data source on initialization. It uses this one QueryRunner object for all servlet requests from multiple different servlets used by the webapp by passing it around as a servlet context attribute. I.e.:

// in servlet context listener (on app initialization)
QueryRunner myQueryRunner = new QueryRunner(myDataSource);
myServletContext.setAttribute("queryRunner", myQueryRunner);

// in the servlets
QueryRunner myQueryRunner = (QueryRunner) myServletContext.getAttribute("queryRunner");
myQueryRunner.query(myStoredProcedure, handler, params)

I am trying to figure out if that is a bottleneck. Should the servlets be instantiating a new QueryRunner with every request instead?

When looking around for an answer I also found this AsyncQueryRunner. But I just got more confused because the explanations in the API docs for QueryRunner and AsyncQueryRunner say the exact same thing.

I looked through the examples here and it seems that it should be instantiated with every request but I am not sure if that is just because it is example code.

In other words, when using DBUtils QueryRunner should I:

  1. Use a single QueryRunner instance for every request? (what I am doing now)
  2. Instantiate a new QueryRunner with every servlet request?
  3. Use a single AsyncQueryRunner instance for every request?

Solution

  • QueryRunner is a thread safe class because it is stateless so you can use a single instance in a multithread environment without any problem.

    All methods are self contained and so there's no need to sinchronize method access so you can also exclude bottlenecks.

    I use it in production environment without problem but my implementation follow the pattern "instantiate a new QueryRunner with every statement" because it's a delegating class with no state so no heavy initialization and no heap consuming and I avoid to use singleton or other shared instance to store such type of class.

    AsyncQueryRunner is also thread safe but its purpose and usage is completely different (see http://commons.apache.org/proper/commons-dbutils/examples.html). It is used to create a non-blocking call for long running statement. It could be useful if your business layer needs to be asynchronous.

    In conclusion: