Does this code create a circular memory reference

2019-07-04 13:46发布

I have the following hypothetical code:

class User < ActiveRecord::Base
  def oauth_consumer
    @oauth_consumer ||= OauthConsumer.new(self)
  end
end

class OauthConsumer
  attr_reader :user, :access_token

  def initialize(user)
    @user = user
    @access_token = OAuth::AccessToken.new(@user.token, @user.secret)
  end

  def get_posts_in_thread(thread_id)
    response = access_token.get("/thread/#{thread_id}/user/#{user.id}")
    JSON.parse(response.body)
  end
end

user = User.new(:token => 'token', :secret => 'secret')

# I want to get the user's posts in thread #12345.
user.oauth_consumer.get_posts_in_thread(12345)

I'm wondering if this creates a circular memory reference, in which user has a reference to the oauth_consumer, and the oauth_consumer has a reference to user, thus making it impossible to be garbage collected?

Or does the underlying GC implementation (REE 1.8.7) handle this case?

1条回答
男人必须洒脱
2楼-- · 2019-07-04 14:37

The following discussion suggests that Ruby's GC appraoch (mark and sweep) copes with circular references:

http://www.ruby-forum.com/topic/85717

查看更多
登录 后发表回答