I am developing a Farm Management system. One of the basic queries is to list the animals by type that are alive (% with%). Below is the method that performs this query.
public List<T> findByInFarm(T model, boolean inFarm) throws DAOException {
List<T> animalList = null;
EntityManager em = JpaHelper.getEntityManager();
Query query = em
.createQuery("SELECT a FROM " + model.getClass().getSimpleName() + " a WHERE a.inFarm = :inFarm");
query.setParameter("inFarm", inFarm);
try {
long start = System.currentTimeMillis();
animalList = (List<T>) query.getResultList();
long end = System.currentTimeMillis();
System.out.println("findByInFarm() demorou " + (end - start) + " millis");
} catch (Exception e) {
throw new DAOException(e.getCause().toString());
} finally {
if (em.isOpen()) {
em.close();
}
}
return animalList;
}
The query returns the expected result, but after running the same query a few times, performance drops a lot. I inserted a inFarm = true
before System.currentTimeMillis()
and one later to measure query performance and rode the test below.
public void test() {
while (true) {
try {
List<Cow> cowList = new Cow().findByInFarm(true);
new Thread().sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below is the result obtained after some repetitions:
- findByInFarm () took 1017 millis
- findByInFarm () took 615 millis
- findByInFarm () took 606 millis
- findByInFarm () took 591 millis
- findByInFarm () took 566 millis
- findByInFarm () took 561 millis
- findByInFarm () took 586 millis
- findByInFarm () took 588 millis
- findByInFarm () took 546 millis
- findByInFarm () took 3036 millis
- findByInFarm () took 4876 millis
- findByInFarm () took 4959 millis
- findByInFarm () took 4904 millis
- findByInFarm () took 4924 millis
- findByInFarm () took 4936 millis
The first queries are very fast but after the tenth repetition time increases a lot. Could anyone give a hint where the possible causes might be?
Note: I'm using Hibernate 5.2, Postgresql 9.4 and Java 8.