0

Let's say I have an EJB for scheduled job.

@Singleton
@Startup
public class MySchedule {

    @Schedule
    public void doSomething() {
        // select oldest 8192 entities (MyEntity.class)
        // and process them
        entityManager.clear(); // should I do this?
    }

    @PersistenceContext
    private EntityManager entityManager;
}

Is it possible those selected entities are kept in the entityManager? Should(Ought) I clear it?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • 2
    doSomething() runs under CMT transaction, and when the method ends, the transaction is committed and the persistence context will be cleared. So no, there is no need to call entityManager.clear() at the end of doSomething(). However, it seems that you intend to do batch processing, then at some point during processing it might be beneficial to call entityManager.clear() to avoid possible memory problems, since the loaded entities accumulate in the "first order" cache until you call entityManager.clear() (see http://stackoverflow.com/questions/13886608/when-to-use-entitymanager-clear). – John Donn Aug 26 '16 at 14:16
  • @JohnDonn Cleared when method ends even with `@Singleton`? – Jin Kwon Aug 26 '16 at 15:26
  • 1
    yes, this should be so. I have also to correct myself: when you do batch processing, it might be beneficial to call **entityManager.flush()** and not entityManager.clear(), because with clear() the modifications made to the entities will be lost, while with flush() the changes are written to the database, the "first order cache" emptied, and the written changes are committed as soon as you leave the doSomething() method. – John Donn Aug 26 '16 at 18:07
  • 1
    Of course, the best thing would be to perform an experiment. One should take an entity which is not cached by the "2-nd order cache" (EhCache or whatever), and see if such entity with a particular id gets loaded from the database every time, if you call doSomething() two times in a sequence (it is better not to trust the logs for this and inspect the traffic to the db with Wireshark, for example), If the call to the db is made only one time, it would mean that the 2nd time the entity is taken from the "first order cache", and that what I say is not true. But there should be two calls to db. – John Donn Aug 26 '16 at 18:32

0 Answers0