New feature: JRuby::Synchronized for thread-safety stuff

After talking with MenTaLguY on IRC about adding some concurrent
collections to JRuby, we came up with a new feature for people to try

require ‘jruby/synchronized’

class MyClass
include JRuby::Synchronized


obj.extend JRuby::Synchronized

the effect of including or extending this new module is that all
method calls against that class’s object (or against that
now-singleton object) will act like they’re wrapped in a Java
synchronized block. No two threads will be able to execute methods
against those objects at the same time (on a per-object basis,

This is definitely blunt tool for threadsafety, and using it
willy-nilly can easily lead to deadlocks (like if you have two
interdependent data structures that are both Synchronized and call
each other). But used appropriately, it provides a pretty simple
(brute-force) way to make a given object or class thread-safe®.

Getting a synchronized collection is now as simple as

foo = {}
foo.extend JRuby::Synchronized

Or perhaps better:

class SyncHash < Hash
include JRuby::Synchronized

Keep in mind that all methods are synchronized, including reads and
methods unrelated to the internal state of the object. In general, the
JVM does a good job of making locks cheap, so I think this is wholly
acceptable for the utility you get.

Comments, suggestions, questions welcome.

  • Charlie

To unsubscribe from this list, please visit: