ActiveRecord, Ruby and Threads

written by Jan on September 21st, 2006 @ 07:10 PM

The last few weeks I have been develloping a new application for the company I work for, Openminds. The program is written in Ruby and utilizes Threading in its working. Since the application needs to talk to a database a lot, and I’m quite tired of rebuilding all the CRUD classes in yet another language. Luckily, since the birth of Rails, Ruby has some new, very nifty classes. One of them is ActiveRecord.

ActiveRecord allows me to access the database in a very easy way. Let me show you. Imagine I have a database table called ‘dogs’, containing the fields race, color and age. To add a new dog to the table, all I have to do in ruby is this

  class Dog < ActiveRecord::Base
  end do |dog|
    dog.race = "Doberman"
    dog.color = "Black"
    dog.age = 1

and voila, I have a new dog. Anyhow, enough showing off the fancy ruby classes and possibilities, I’m sure you’ve all heard about it before. So as I said my application uses Threading. And some of those threads’d like to talk to my database. Only, ActiveRecord didn’t like that all that much. The moment too many threads were talking to it, it gave up and raised an ActiveRecord::StatementInvalid error. Not very descriptive to say the least. After a lot of googling I found some sites saying ActiveRecord is not threadsafe. The rails site however, kept telling me it WAS actually threadsafe. In a last attempt to find out what was going on, I started looking at the code. And that’s when I found it. Badly documented and not very googlable, but its there:

  # Determines whether or not to use a connection for each thread, 
  # or a single shared connection for all threads.
  # Defaults to false. Set to true if you're writing a threaded application.
  cattr_accessor :allow_concurrency
  @@allow_concurrency = false

So that was it. By default, ActiveRecord is NOT ThreadSafe, but you can make it threadsafe very easily. The only thing you need is:

  ActiveRecord::Base.allow_concurrency = true
and your multithreading application can talk to ActiveRecord!

PS: This post is in english so poor googlers can find the solution to their threading problem ;)


  • Martijn Engler on 15 Oct 21:55

    GeSHi Error: GeSHi could not find the language ruby (using path /files/friends/ (code 2)

    Very interesting indeed! ;-)

  • jan on 15 Oct 22:06

    Allready fixed ;)

  • a poor googler on 27 Oct 19:20

    thanks very much :)

  • You can thread ActiveRecord apparently on 05 Nov 01:05

    [...] Found on this useful blog. [...]

Comments are closed