Search code examples
ruby-on-railsrubyjrubythreadcontext

Jruby thread context instance association


I am trying to eval javascript in ruby.

config/initializer/initializer_context.rb
  js_str = 
  EXEC_PP_CONTEXT = ExecJS.compile("function test_add(param) { return param.a+ param.b;}")

and then in my controller I am using :

data_hash = {:a=>4,:b=>5}
EXEC_PP_CONTEXT.exec("return test_add(#{data_hash.to_json})")

But I occasionally get this error ( 1 in 100 requests)

can not use Context instance already associated with some thread

Stack:

  • jruby-1.7.3 in ruby 1.9 mode
  • trinidad server with jruby_min_runtimes & jruby_min_runtimes as 1
  • rails 3.2.13
  • therubyrhino 2.0.2

If I am already setting max runtime and min runtime to 1 shouldn't it avoid this problem in first place ?


Solution

  • finally figured out by reading Mozilla rhino's code: https://github.com/matthieu/rhymeno/blob/master/src/org/mozilla/javascript/Context.java#LC416

    static final Context enter(Context cx, ContextFactory factory) Basically the method counts the number of threads that are inside the context ( using it / executing it) and if another thread tries to enter it , it throws an error.

    To avoid the problem and achieve concurrency , we lazily created one context per thread using ruby's Thread[:current][:some_js_context] = blah_