Wednesday, February 21, 2007

Thread Safety - How to Tell

In a multithreaded environment, instances of non thread safe classes are susceptible to two kinds of misbehavior: write/write conflicts and read/write conflicts. From any of these two conflicts, you can tell that the class is not thread safe.

Write/write conflicts

Imagine two threads are trying to write to the same object's instance variables concurrently. If the thread scheduler interleaves these two threads in just the right way, the two threads will inadvertently interfere with each other, yielding a write/write conflict. In the process, the two threads will corrupt the object's state.

Read/write conflicts

This kind of conflict arises when an object's state is read and used while in a temporarily invalid state due to the unfinished work of another thread.

This is like the ACID characteristics of transactions. As long as it takes two or more steps to move an instance from one state to another state, the class is very unlikely thread safe.

No comments: