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

**URL:** <https://www.ruby-forum.com/t/new-feature-jruby-synchronized-for-thread-safety-stuff/185707>\
**Category:** JRuby\
**Created:** [March 24, 2010, 9:16pm UTC](https://www.ruby-forum.com/t/new-feature-jruby-synchronized-for-thread-safety-stuff/185707 "2010-03-24T21:16:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![headius](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/7c8e57/32.png) [@headius](https://www.ruby-forum.com/u/headius)\
**Post date:** [March 24, 2010, 9:16pm UTC](https://www.ruby-forum.com/t/new-feature-jruby-synchronized-for-thread-safety-stuff/185707/1 "2010-03-24T21:16:05Z")

</div>

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

require ‘jruby/synchronized’

class MyClass  
include JRuby::Synchronized  
…

or

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,  
obviously).

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  
end

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:

```
http://xircles.codehaus.org/manage_email
```
