Sharing Mutable Objects Using a Safe Accessor Service

On page 54 in his distinguished book "Java Concurrency In Practice," Brian Goetz describes how objects can be safely shared across threads. He lists four options:

  • The object is thread-confined, meaning updates to the object are performed by only one owning thread
  • The object is shared read-only, meaning this object only needs one-time publication
  • The object is inherently thread-safe, meaning it performs synchronization internally
  • The object is guarded by some lock

In this post, I will describe a variant that falls into the fourth category. The objects shared are not thread-confined, not read-only, and aren't synchronized internally. I am going to use a read-write lock to guard the object's state. As the presented technique is highly concurrent, it will not require synchronized blocks and gauruntees that no needless thread contention will slow down application performance. Without using synchronized, it is still garanteed that any change will be visible across all threads that share the object instances; this is achieved by applying certain rules to the shared objects' mutable state.