Memory Leak in PersistenceContext

Viewed 36

I got a serious problem with persisting entities to database. No matter how i handle the Repository-Layer i always have the problem with increasing usage in Java Heap.

My goal is simple: No OutOfMemoryException with this pseudo Code:

while(true) { repo.save(someEntity) }

Code in loop should be transactional. That means: after each loop there should be a transaction commit to database.

Sidenote: in my real case it is not a permanent while(true) loop but the process can last up to 3h. I just test the behaviour of the memory with a simple function like that.

The problem is an increasing usage in Java Heap. In this example i executed the application with: java -jar -Xmx128M -Xms128M app.jar

enter image description here

What i already tried:

Creating a new EntityManger for each transaction

val em = entityManagerFactory.createEntityManager()
em.transaction.begin()
em.persist(someEntity)
em.transaction.commit()
em.close

Working with @Transactional

@Service
class Foo {
    @Autowired
    private Bar bar;
    @Transactional(propagation = Propagation.NEVER)
    public void loop() {
        while (true) {
           bar.save();
        }
    }
}
@Service
class Bar {
    @Transactional(propagation = Propagation.REQUIRED)
    public void save() {
        repo.save();
    }
}

Does somebody know what I am doing wrong? Is it even possible to do such task in Spring Boot?

1 Answers

JPA caches persisted entities by default. To prevent OutOfMemoryException when persisting many entities, set caching to BYPASS.

EntityManager em = ...;
em.setProperty("javax.persistence.cache.storeMode", "BYPASS");
Related