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?
asked May 7, 2020 at 14:20
\$\endgroup\$
1
  • \$\begingroup\$ Please post a sample app to reproduce the problem. \$\endgroup\$ Commented Jun 1, 2020 at 22:38

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.