views:

333

answers:

2

Hello,

I'm developing a Flex application with BlazeDS and I'm experiencing memory leak when using java to query from MySQL in hibernate. Can anyone tell me how to deal with this memory leak? It seems that each time query is invoke java.exe takes more memory.

Thanks

Sample of my java

factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
EntityManager em = factory.createEntityManager();

Query find = em.createNamedQuery("Plan.findByStudentId");
find.setParameter("studentId", studentID);

List<Plan> c = find.getResultList();

return c;
+2  A: 

I assume you are leaving your EntityManager open after you return the data to flex, which in turn means that your MySQL Connection remains open. That's where the memory leak most likely comes from. So - close your EntityManager.

In anoter comment you said that you are using GlassFish. That's a whole new scenario. Is your class this a Servlet? An EJB?. GlassFish is supposed to manage your EntityManagers (if the class itself is managed), so you don't have to create or close it yourself. In such cases use @PersistenceContext annotation to inject the EntityManager (instead of using Persistence.create..)

But the thing you must do whatever the setup, is to start a profiler and see where is this memory allocated.

Bozho
Tried it but still doesn't work. I put em.close(); at one line before every return but the memory still grows unreasonably.
Pii
did it close successfully?Have in mind that the memory could grow to some point until garbage-collected, so, as noted in the comment on your question, wait to see if an OutOfMemoryError would occur.
Bozho
Can you give me a full example of how things should look like? currently, I just addedem.clear(); em.close(); factory.close();before return and it seems to help more or less. Is this correct?
Pii
if it works for you, then OK. But tell me what is this class? Is it simply a POJO, which is loaded by BlazeDS? Or is it a servlet/EJB? In the former case perhaps the manual handling is appropriate. In the latter - I'll give you some links.
Bozho
A: 

Hi you just need to out your code in a try catch block and close the entity manager.

try{
    if(em !=null){
        em.close();
    }
} catch(Exception e){
    e.printStackTrace();
} finally {
    em.close();
}
akellakarthik
Now I got java.lang.IllegalStateException : EntityManager is closedI'm using Glassfish v3 by the way. Is there anything to do with this?
Pii