简体   繁体   中英

Memory Leak in PersistenceContext

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

在此处输入图片说明

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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM