1

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 ?

Abhay Kumar
  • 1,582
  • 1
  • 19
  • 45
Gaurav Shah
  • 5,223
  • 7
  • 43
  • 71
  • it's probably coming from Rhino itself not JRuby - uses a context per thread to manage state as well ... – kares Feb 20 '15 at 17:39

1 Answers1

0

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_

Gaurav Shah
  • 5,223
  • 7
  • 43
  • 71
  • since you already answered on your own you should also change the title to somehow better reflect what this q is about ... – kares Feb 24 '15 at 13:18