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.
Whether my understanding is correct?
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?- Or can I refactor the initial version of
getData
differently?
-
\$\begingroup\$ Please post a sample app to reproduce the problem. \$\endgroup\$gtiwari333– gtiwari3332020年06月01日 22:38:17 +00:00Commented Jun 1, 2020 at 22:38