0

I am using JPA to persist records to Oracle database. Everytime I run the application, it goes to a particular directory and parse every single file in there and load into tables. Usually there are thousands of files to be processed.

An new EntityManagerFactory is created every time I process a file and when the record is inserted. Therefore, the EMF is opened thousands of times every run. When I am debugging it I discovered creation of EMF is the most time consuming step which takes more than 90% of the run time. On average creating a new EMF takes about 2-3 seconds. Maybe I should just open EMF connection once at the beginning of the application before iteration of files starts? Is it good practice to have EMF open the whole time?

ddd
  • 4,665
  • 14
  • 69
  • 125
  • 1
    An EntityManagerFactory is thread safe, and as you've discovered, has a lot of setup in obtaining, loading and verifying everything required for a persistence unit. EntityManagers are light weight but not thread safe - these objects should be obtained when needed, while the EMF centrally/statically loaded. – Chris Jul 13 '16 at 16:55
  • @Chris Thanks for explaining the difference. Please make it an answer and I will close it. – ddd Jul 13 '16 at 18:25

1 Answers1

1

Pulled from my comment: An EntityManagerFactory is thread safe, and as you've discovered, has a lot of setup in obtaining, loading and verifying everything required for a persistence unit. EntityManagers are light weight but not thread safe - these objects should be obtained when needed, while the EMF centrally/statically loaded.

Chris
  • 20,138
  • 2
  • 29
  • 43