Hibernate out of memory exception while processing large collection of elements

后端 未结 4 1853
野性不改
野性不改 2020-12-18 05:25

I am trying to process collection of heavy weight elements (images). Size of collection varies between 8000 - 50000 entries. But for some reason after processing 1800-1900 e

相关标签:
4条回答
  • 2020-12-18 05:57

    You have confused flushing with clearing:

    • flushing a session executes all pending statements against the database (it synchronizes the in-memory state with the database state);

    • clearing a session purges the session (1st-level) cache, thus freeing memory.

    So you need to both flush and clear a session in order to recover the occupied memory.

    In addition to that, you must disable the 2nd-level cache. Otherwise all (or most of) the objects will remain reachable even after clearing the session.

    0 讨论(0)
  • 2020-12-18 05:57

    This article solved my issue

        Session session = sessionFactory.getCurrentSession();
          ScrollableResults scrollableResults = session.createQuery("from DemoEntity").scroll(ScrollMode.FORWARD_ONLY);
          int count = 0;
          while (scrollableResults.next()) {
           if (++count > 0 && count % 100 == 0) {
            System.out.println("Fetched " + count + " entities");
           }
           DemoEntity demoEntity = (DemoEntity) scrollableResults.get()[0];
           //Process and write result
           session.evict(demoEntity);//important to add this
          }
         }
    

    bulk fetching hibernate

    1. Use hibernate ScrollableResult
    2. Use evict

    BTW I tried the statless solution it gave me this exception i did not how to solve ( may be you can improve this answer) Exception details is here

    org.hibernate.SessionException: collections cannot be fetched by a stateless session
    

    So i tuned with sleep(delay) as its a back ground process and very long with low resources on server i have to cool down cpu; with midnight work ( none rush hours).

    0 讨论(0)
  • 2020-12-18 05:59

    I don't know why you think committing a transaction frees heap memory. Running garbage collection does that.

    OOM error can happen if your perm gen is exhausted.

    The easy answer is to change your min and max heap sizes and perm gen size when you start the JVM and see if it goes away.

    I'd recommending getting a profiler, like VisualVM, and seeing what is consuming your memory at runtime. It should be easy to fix.

    I'd guess that you're trying to commit too large a chunk at once. Break it up into smaller pieces and see if that helps.

    0 讨论(0)
  • 2020-12-18 06:16

    Try using session.clear() which "Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions. Do not close open iterators or instances of ScrollableResults"

    0 讨论(0)
提交回复
热议问题