|
|
||
Tom White's BlogSeptember 2006 ArchivesAre your beans thread-safe?Posted by tomwhite on September 21, 2006 at 01:55 PM | Permalink | Comments (27)[Update: changed wording per comments to fix error.] Dependency injection is pretty well established these days, with plenty of Inversion of Control containers available to manage your beans. I'm currently reading Java Concurrency in Practice by Brian Goetz et al, which got me thinking about the thread-safety of large object graphs managed by IoC containers.
In most applications I've seen, the common usage pattern is to use dependency injection to wire up your object graph in one go when the application starts. After that the application uses the object graph, and effectively treats it as being immutable. For example, in an application for buying books we might have a
The problem is that it's not clear that this code is thread-safe. Unless the container publishes the
Thankfully, this is easy to fix. We can mark the
Alternatively, we can use constructor injection and
The Future
So could the IoC container providers take steps to ensure that application developers don't have to worry about thread safety in wiring up object graphs? Possibly, although at the time of writing it is less than clear whether the popular containers do or not. Tim Peierls, one of the authors of Java Concurrency in Practice, wrote in a email to me that "Until it's proven safe, I have adopted a rule that all such setter-injected effectively immutable fields must be volatile." He also suggested marking the field with an annotation, such as | ||
|
|