Sunday, October 5, 2008

Thread-safe simple lifecycle.

The subject today is not rocket science,  but it's been common enough through the years to deserve a post :). The problem is as follows: we have and object with a very simple lifecycle (on and off) and we need (or want) the status-changing methods (start and stop) to be thread-safe.

Of course, we can just make start and stop synchronized but, can we do better? Ok, let's polish our list of desired features:
  • We want a generic solution. We only want to write the transition code (starting up and shutting down) without worrying about thread-safety, getting it for free from the solution.
  • We want to minimize synchronization, and ideally avoid it.
  • If we can't avoid synchronization, we forbid calling alien methods from synchronized regions (to avoid unforeseen problems in the future).
So, I've checked-in a possible solution. It avoids synchronization by adding some transient states and using AtomicReference (the java.util.concurrent.atomic package contains equivalent classes for different types). More specifically, the solution is based on the compareAndSet method, which besides the properties described in the documentation, has the added benefit of being idempotent, a property that really simplifies reasoning in concurrent and distributed systems, at very different levels of abstraction.

Update: Changed svn links to tagged version.

No comments: