Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this code create a circular memory reference in Ruby?

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?

like image 362
dbalatero Avatar asked May 23 '26 19:05

dbalatero


1 Answers

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

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

like image 99
sheldonh Avatar answered May 25 '26 12:05

sheldonh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!