Clojure:使用 eval 发生内存泄漏
我的应用程序评估从远程客户端收到的引用表达式。随着时间的推移,我的系统内存不断增加,最终崩溃。我发现:
当我在docker容器中从Clojure的nrepl执行以下代码时:
(dotimes [x 1000000] ; or some arbitrary large number
(eval '(+ 1 1)))
容器的内存使用量不断上升,直到达到限制,此时系统将崩溃。
我该如何解决这个问题?
还有另一个线程提到了这种行为。其中一个答案提到了使用 tools.reader
,如果我需要执行代码,它仍然使用 eval
,导致同样的问题。
My application evaluates quoted expressions received from remote clients. Overtime, my system's memory increases and eventually it crashes. What I've found out is that:
When I execute the following code from Clojure's nrepl in a docker container:
(dotimes [x 1000000] ; or some arbitrary large number
(eval '(+ 1 1)))
the container's memory usage keeps rising until it hits the limit, at which point the system will crash.
How do I get around this problem?
There's another thread mentioning this behavior. One of the answers mentions the use of tools.reader
, which still uses eval
if I need code execution, leading to the same problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有简单的方法可以解决这个问题,因为每次调用
eval
都会创建一个新类,即使您正在评估的表单完全相同。 JVM 本身不会删除新类。有两种方法可以避免这种情况:
eval
(例如,创建您自己的 DSL 或功能有限的您自己的eval
版本)或至少减少使用频率,例如,通过批处理您需要评估There's no easy way to get around this as each call to
eval
creates a new class, even though the form you're evaluating is exactly the same. By itself, JVM will not get rid of new classes.There are two ways to circumvent this:
eval
altogether (by e.g. creating your own DSL or your own version ofeval
with limited functionality) or at least use it less frequently, e.g. by batching the forms you need to evaluate我不知道
eval
内部到底是如何工作的,但根据我的观察,我认为你的结论是不正确的,而且尤金的言论“就其本身而言,JVM 不会摆脱新类”似乎是错误的。
我使用 -Xmx256m 运行您的示例,一切顺利。
我检查了您链接的问题,他们说这是元空间 那是增长而不是堆。
因此,我观察了元空间,它的使用量在增长,但也在缩减。
您可以在这里找到我的实验以及来自 JMC 控制台的一些图表: https://github.com/jumarko/clojure-experiments/commit/824f3a69019840940eaa88c3427515bcba33c4d2
注意:为了运行此实验,我在 macOS 上使用了 JDK 17.0.2
I don't know how
eval
exactly works internally,but based on my observations I don't think your conclusions are correct and also Eugene's remark "By itself, JVM will not get rid of new classes" seems to be false.
I run your sample with -Xmx256m and it went fine.
I checked the question you linked and they say it's Metaspace that is growing not heap.
So I observed the Metaspace and it's usage is growing but also shrinking.
You can find my experiment here together with some graphs from JMC console: https://github.com/jumarko/clojure-experiments/commit/824f3a69019840940eaa88c3427515bcba33c4d2
Note: To run this experiment, I've used JDK 17.0.2 on macOS