3
\$\begingroup\$

I have a API and the corresponding service method is like this:

@Transactional
public List<Object> getData(args) {
    databaseStatements;
    databaseStatementsOnOtherThread();
    NetworkCallStatements;
    CPUBoundStatements(calculation, sorting, etc)
}

With this setup, each request holds a database connection as I have @Transactional annotation on the method. So If I have 5 connections to database, I was able to serve only 5 requests concurrently. Other requests are waiting for database connection and gets timed-out.

I have refactored this method to avoid blocking of database connection during network and CPU tasks:

public List<Object> getData(args) {
    getDataFromDatabase1();
    databaseStatementsOnOtherThread();
    getDataFromDatabase2();
    NetworkCallStatements;
    CPUBoundStatements(calculation, sorting, etc)
}

/* The below methods are from different classes as @Transactional will not effect in same class */
@Transactional
public Data1 getDataFromDatabase1() {
    //some statements
}

@Transactional
public Data2 getDataFromDatabase2() {
    //some statements
}

As I have removed @Transactional annotation from main method and added to sub methods having only database calls, connection will not be blocked during network calls and CPU tasks. This gives a very good result as I am able to serve more no of requests with less no of connections and the failure rate also reduced.

Now the problem is when there is one or two requests at a time (or very few requests), the response time has been increased from the previous version. What I feel is, earlier I was obtaining database connection one time, now obtaining 2 or more time(one for each sub methods) which may cause this slowness.

  1. Whether my understanding is correct?

  2. How can I organize the sub methods into a single method to obtain the connection only once? All these sub methods are returning different data types and also I cannot have them in the same class due to @Transactional limitations. Any idea to overcome the above problems?

  3. Or can I refactor the initial version of getData differently?
\$\endgroup\$
  • \$\begingroup\$ Please post a sample app to reproduce the problem. \$\endgroup\$ – gtiwari333 Jun 1 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.