Kathir
Kathir

Reputation: 2903

Hibernate evict() vs setting object to null at the end

We are processing huge number of entity objects in the loop. At the end currently we are setting the objects to null to be eligible for garbage collection.

  1. Is it right or we need to use hibernate evict() ?
  2. What is the difference between evict an object vs marking the object as null at the end of the loop ?

Please help to understand in detail.

Thanks.

Upvotes: 1

Views: 298

Answers (1)

Douglas Gardim
Douglas Gardim

Reputation: 430

Only setting the entity object to null will not help since there will be still a reference to it in the Hibernate's 1st level cache. So it will not make it eligible for garbage collection.

When you evict the object, you will take it out of the hibernates cache and then it will be candidate for garbage collection.

So, if you want it to be garbage collected you will have to both mark the object as null (clear your reference) AND evict it from hibernate's cache (clear hibernate's reference).

As a side note, besides freeing memory space (after the garbage collection), taking the entity out of the cache can save a lot of CPU time since this cache is also constantly processed in dirty checkings made by Hibernate every time you make new queries.

Upvotes: 2

Related Questions