Threading some queries

I set up a quick multi-thread query test for a complex model entity made of several hibernate table entities. What I was trying to accomplish was a faster retrieval by running the queries in parallel. Spring JPARepository is the underlying querying mechanism. Here’s the higher level entity:

/*
* LookupEntity is a composite pojo of TableX instances,
* TableX instances are just any jpa/hibernate entities
* that share the same id (for simplicity)
*/
public LookupEntity {
private Integer id;
private Table1 table1;
private Table2 table2;
private Table3 table3;

public LookupEntity(){}

public Table1 getTable1() {return table1;}
public void setTable1(Table1 table1) {this.table1 = table1;}

public Table2 getTable2() {return table2;}
public void setTable2(Table2 table1) {this.table2 = table2;}

public Table3 getTable3() {return table3;}
public void setTable3(Table3 table3) {this.table3 = table3;}
}

In my service method is the threading test. I wrote a quick @TimeMethod annotation and point cut to time the method:

/*
* getLookupThreaded will run TableX repository methods to populate
* the TableX objects in a LookupEntity
*/
@TimeMethod
public LookupEntity getLookupThreaded(final Integer id) {
final LookupEntity lookupEntity = new LookupEntity(id);

Runnable r1 = new Runnable() {
public void run() {
lookupEntity.setTable1(table1Repository.findOne(id));
};
};
Runnable r2 = new Runnable() {
public void run() {
lookupEntity.setTable2(table2Repository.findOne(id));
};
};
Runnable r3 = new Runnable() {
public void run() {
lookupEntity.setTable3(table2Repository.findOne(id));
};
};

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);

t1.start();
t2.start();
t3.start();

return lookupEntity;
}

This worked pretty well but would still need more scaling management with the threads if a server was going to hit the method 10k times. But what I found was more weaknesses in my table designs and indexing as opposed to coding deficiencies after turning on jpa and hibernate logging. Personally, I avoid threading and non injection container singletons like the plague unless absolutely necessary because they introduce, many times, unnecessary complexity. But if I were to write some low connection count analysis procedures; maybe doing big data style calculations in a job, I might consider threading to save time.

Comments are closed.