views:

20

answers:

1
public class SoapMessageProcessor {

private EntityManager em;
private static final Logger logger = Logger.getLogger(SoapMessageProcessor.class);

public SoapMessageProcessor() {
    try {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Auditing");
        em = emFactory.createEntityManager();
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage());
    }
}

Will this leak memory, when this class is being invoked from a asynchronous EJB call?

So I thought of making the EntityManager and EntityManagerFactory static class members. Will that solve the issue?

Some help needed here. When I ran JProfiler. It says that this area is a Hot spot.Especially the createEntityManagerFactory.

Any help in fixing this leak is appreciated.

+1  A: 

I don't think you close either the EMF or the EM.

try {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Auditing");
        em = emFactory.createEntityManager();
        // do whatever you need to do
        em.close();
        emFactory.close();
} catch (Exception ex) {
        throw new RuntimeException(ex.getMessage());
}

You shouldn't keep an entity manager in a field. It's kind of a "use once and then throw away" kind of object. You can, however, keep an EMF reference.

How often are you creating SoapMessageProcessor instances?

Are you using any kind of dependency injection framework? It'll make your life much simpler.

The Alchemist
The SOAPMessageProcessor gets called as a asynchronous call from Jboss extensions. So when ever the user makes a request. The SOAP message processor is getting invoked for logging purpose. The Jboss extension creates concurrent threads to access message processor.
Vanchinathan Chandrasekaran
@Vanchinathan: OK, it sounds like you'll only have a single instance of `SoapMessageProcessor`. In that case, create your EMF in the `create()` method of the class, and `close()` your EMF in the `destroy()` method. Create (and don't forget to close!) an EM in your logging method. Creating and closing a EM is a cheap operation, so you should be fine.
The Alchemist
Hi, I declared the EMF as static and initialized it in the static block. So it will be available as long as the class lives. For some reason, the code does not have lifecycle methods. So I followed this approach.
Vanchinathan Chandrasekaran
Good to hear! If you have the time, I would recommend trying to figure out how you could make `SoapMessageProcessor` a managed EJB bean or something, so the EMF would get closed.
The Alchemist