Instantiating DBUtils QueryRunner

I have a web service that creates a QueryRunner instance with a datasource on initialization. It uses this one object QueryRunner

for all servlet requests from several different servlets used by the webapp, passing it 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 find out if this is the bottleneck. Should servls create a new one QueryRunner

with every request?

While searching for an answer, I also found this AsyncQueryRunner . But I'm just confused because the explanations in the API docs for QueryRunner and AsyncQueryRunner say the same thing.

I've looked at the examples here and it seems like it should be generated with every request, but I'm not sure if it's just because it's a sample code.

In other words, when using DBUtils QueryRunner

, I have to:

  • Use one instance QueryRunner

    per request? (What I am now)
  • Create a new one QueryRunner

    with every servlet request?
  • Use one instance AsyncQueryRunner

    per request?
+3


source to share


1 answer


QueryRunner is thread safe as it is stateless, so you can use one instance in a multithreaded environment without any problem.

All methods are self-contained and therefore there is no need to synchronize access to the method so you can also eliminate bottlenecks.

I use it in production with no problem, but my implementation follows the "create a new QueryRunner with every expression" pattern because it is a stateless delegating class so there is no strong initialization and heap and I avoid using a singleton or other shared instance to store such class type.



AsyncQueryRunner is also thread safe, but its purpose and use are completely different (see http://commons.apache.org/proper/commons-dbutils/examples.html ). It is used to create a non-blocking call for an agent with a long run. This can be useful if your business layer needs to be asynchronous.

Finally:

  • using a single QueryRunner instance from multiple threads (each request from the same thread?) has no contraindications, but also has no advantage, but it takes a little code to manage this instance.
  • using a new QueryRunner instance for each thread, or even for each statement you want to delegate through it, has two main advantages: easy and localized use, and instances are not kept in memory when not needed.
  • AsyncQueryRunner requires cumbersome query response management, so only use it if you need asynchronous behavior in your business code.
+5


source







All Articles