循环中的Ruby代码内存泄漏

时间:2016-06-22 06:02:02

标签: ruby-on-rails ruby ruby-2.1

下面的代码有内存泄漏。它在ruby 2.1.1下运行。我无法找到实际的泄漏。

q = Queue.new("test")
while true do
  m = q.dequeue
  body = JSON.parse(m.body)
  user_id = body["Records"][0]
  user = V2::User.find(user_id)
  post = V2::Post.find(post_id)  
end

运行几个小时后,我添加了GC.start,但它没有解决问题

q = Queue.new("test")
while true do
  m = q.dequeue
  body = JSON.parse(m.body)
  user_id = body["Records"][0]
  user = V2::User.find(user_id)
  post = V2::Post.find(post_id) 
  GC.start 
end

我不知道如何找到实际的内存泄漏。

2 个答案:

答案 0 :(得分:1)

尝试从下往上删除行,并查看内存是否仍然存在泄漏。内存泄漏可能来自find方法,或者可能是JSON.parse(极不可能),或者是自定义Queue数据结构。如果在删除所有行后仍然存在内存泄漏,则可能来自工作程序本身和/或运行工作程序的程序。

q = Queue.new("test")
while true do
  m = q.dequeue # Finally remove this and stub the while true with a sleep or something
  body = JSON.parse(m.body) # Then remove these two lines
  user_id = body["Records"][0]
  user = V2::User.find(user_id) # Remove the bottom two lines first
  post = V2::Post.find(post_id)
end

答案 1 :(得分:0)

我打赌问题在于引入的局部变量(原文如此!)。摆脱user_idpost_id,它可能会停止泄漏:

# user_id = body["Records"][0]
# user = V2::User.find(user_id)
user = V2::User.find(body["Records"][0]) # sic!

原因是Ruby stores objects in RValues

相关问题