简体   繁体   English

PersistenceContext 中的内存泄漏

[英]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.无论我如何处理存储库层,我总是遇到在 Java 堆中增加使用率的问题。

My goal is simple: No OutOfMemoryException with this pseudo Code:我的目标很简单:没有 OutOfMemoryException 与这个伪代码:

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.旁注:在我的真实情况下,它不是一个永久性的 while(true) 循环,但该过程可以持续长达 3 小时。 I just test the behaviour of the memory with a simple function like that.我只是用这样一个简单的函数来测试内存的行为。

The problem is an increasing usage in Java Heap.问题是在 Java 堆中的使用越来越多。 In this example i executed the application with: java -jar -Xmx128M -Xms128M app.jar在这个例子中,我执行了应用程序: java -jar -Xmx128M -Xms128M app.jar

在此处输入图片说明

What i already tried:我已经尝试过的:

Creating a new EntityManger for each transaction为每笔交易创建一个新的 EntityManger

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

Working with @Transactional使用@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?甚至有可能在 Spring Boot 中完成这样的任务吗?

JPA caches persisted entities by default. JPA 默认缓存持久化实体。 To prevent OutOfMemoryException when persisting many entities, set caching to BYPASS .要在持久化多个实体时防止出现 OutOfMemoryException, 请将缓存设置为 BYPASS

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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