Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why class variable of Application Controller in Rails is re-initialized in different request

I have my Application Controller called McController which extends ApplicationController, and i set a class variable in McController called @@scheduler_map like below:

class McController < ApplicationController
  @@scheduler_map = {}
  def action
    ...
  end
  private
  def get_scheduler(host, port)
    scheduler = @@scheduler_map[host+"_"+port]
    unless scheduler
      scheduler = Scheduler.create(host, port)
      @@scheduler_map[host+"_"+port] = scheduler
    end
    scheduler
  end
end

but i found that from second request start on @@scheduler_map is always an empty hash, i run it in development env, could someone know the reason? is that related to the running env?

Thank you in advance.

like image 946
ywenbo Avatar asked Feb 24 '11 13:02

ywenbo


1 Answers

You answered your own question :-)

Yes this is caused by the development environment (i tested it) and to be more precise the config option "config.cache_classes = false" in config/environments/development.rb

This flag will cause all classes to be reloaded at every request. This is done because then you dont have to restart the whole server when you make a small change to your controllers.

You might want to take in consideration that what you are trying can cause HUGE memory leaks when later run in production with a lot of visits. Every time a user visits your site it will create a new entree in that hash and never gets cleaned. Imagine what will happen if 10.000 users have visited your site? or what about 1.000.000? All this data is kept in the systems memory so this can take a lot of space the longer the server is online.

Also, i'm not really sure this solution will work on a production server. The server will create multiple threats to handle a lot of visitors on the same time. I think (not sure) that every threat will have his own instances of the classes. This means that in treat 1 the schedule map for ip xx might exist but in treat 2 it doesn't. If you give me some more information about what this scheduler is i might be able to give a suggestion for a different solution.

like image 176
Danny Hiemstra Avatar answered Nov 04 '22 13:11

Danny Hiemstra