Is it possible for me to write a JRuby script within my Rails app and use JRuby just for that script/class?

StackOverflow https://stackoverflow.com/questions/20827082

Question

I have a Rails application that is importing data from various third parties. The jobs are taking a long time and I am looking into how I can use threads to speed this up. I know nothing about Java so apologies if this makes no sense.

Was it helpful?

Solution

No, JRuby is an alternate Ruby interpreter, so you cannot "switch" to it in the middle of running MRI (the standard Ruby interpreter, written in C).

You can create threads in MRI, but many people use a background job queue to handle this type of problem. If you really wanted to, you could also write a second application in JRuby that your first application made remote calls to.

OTHER TIPS

Yes, you can, as long as you intend to run it in a separate process like a rake task for example,

in Gemfile you'll have to handle both options where gem sets are different, for example:

platform :ruby do
  gem "pg"
  gem "ruby-oci8", '>= 2.1.4'
end

platform :jruby do
  gem "activerecord-jdbcpostgresql-adapter"
end

and you need to decide what to do with Gemfile.lock. One option is to keep 2 Gemfile.lock on git, one for JRuby gems and one for MRI Ruby gems - Gemfile.lock.mri and Gemfile.lock.jruby and then symlink accordingly when running bundle.

The other question is if you should, the above approach is a bit finicky and I'm generally using it for building gems or for playing with porting an app to JRuby.

Spawning multiple processes and background job queues is generally how things are done in MRI Ruby, it seems an overkill to introduce a whole new ruby for purpose of a single import task.

That said, I've had situations (on massive data imports done through ruby) where proper multithreading would have saved me a LOT of hassle, but in the end I always fell back to partitioning the problem and running it in separate processes (every odd id in one rake task, every even id in another, for example - bear in mind you might need to rebuild tables in database if you do this or possibly face very slippery regression issues, do a benchmark definitely).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top