java 会话关闭后如何强制休眠释放内存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/928366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force hibernate to release memory once the session is closed?
提问by StudioEvoque
We've just recently started using Hibernate and are still getting used to the way it works.
我们最近才开始使用 Hibernate,并且仍在习惯它的工作方式。
On of the things we've seen is that even after all sessions are closed and references have gone out of scope, hibernate still seems to maintain the previously used database values in it's cache.
我们所看到的事情之一是,即使在所有会话都关闭并且引用已经超出范围之后,hibernate 似乎仍然在它的缓存中维护以前使用的数据库值。
We have code that reads from a set of tables in multiple passes. Because all the memory is freed very sparingly, the later passes slow down to a crawl.
我们有代码可以多次读取一组表。因为所有内存都被非常谨慎地释放,所以后面的传递速度会减慢到爬行。
Is there any way to force Hibernate to clear its cache ?
有没有办法强制 Hibernate 清除其缓存?
An explicit call to System.gc() doesn't help. (Yes, I know it is a suggestion)
对 System.gc() 的显式调用无济于事。(是的,我知道这是一个建议)
Additional Info: We've explicitly disabled the second-level cache.
附加信息:我们已明确禁用二级缓存。
回答by Rob H
You could try calling Session.clear to force a clear of the first-level cache. Be sure to call Session.flush first to write any pending changes to the database. If that "fixes" the problem, then I suspect something is still holding a reference to the session, preventing the objects in the cache from being garbage-collected. You may need to obtain a heap dump of your program to track down the leak.
您可以尝试调用 Session.clear 强制清除一级缓存。确保首先调用 Session.flush 将任何挂起的更改写入数据库。如果这“修复”了问题,那么我怀疑某些东西仍然持有对会话的引用,从而防止缓存中的对象被垃圾收集。您可能需要获取程序的堆转储以追踪泄漏。
回答by David Taylor
Hibernate also has an optional second level cache which could be at play. I agree with Rob, the easiest way to find out is to see what is still in memory after the session ends.
Hibernate 还有一个可选的二级缓存,可以发挥作用。我同意 Rob 的观点,找出问题的最简单方法是在会话结束后查看内存中的内容。
My current favorite tool for this is YourKitwhich is commercial and not exactly cheap. They used to offer (and may still offer) a personal license option which was very inexpensive ($99 IIRC). I have used YourKit for precisely this task when troubleshooting heap usage problems with Alfresco ECM. There are other tools available (e.g. CodeGear JGears) which I understand also work very well.
我目前最喜欢的工具是YourKit,它是商业的,而且并不便宜。他们曾经提供(并且可能仍然提供)非常便宜的个人许可证选项(99 美元 IIRC)。在对 Alfresco ECM 的堆使用问题进行故障排除时,我正是使用 YourKit 来完成这项任务的。还有其他可用的工具(例如 CodeGear JGears),我理解它们也能很好地工作。
You might consider using a product in evaluation mode - if this finds your problem it might earn its keep ;)
您可能会考虑在评估模式下使用产品 - 如果这发现您的问题,它可能会继续存在;)

