When you make thread-safe classes, you have to keep in mind that multiple threads could be trampling through the methods of your class. This requires special care in designing and coding these classes, becuase there is no way of knowing what thread will invoke what method (and in what sequence) on an object of this class. You have to take into account all possible scenarios or design in such a way that the number of possible states that your object can reach is minimized. I prefer to use the smart solution and design in such a way that the number of states my object can reach is minimized, that way I don’t have to think about too many possibilities of what might happen when multiple threads are trampling through the same instance of my class.
In order to make thread-safe classes there are a few simple rules to follow:
- Mutator method access to any shared objects must be synchronized.
- Accessor method access to any shared objects need not be synchronized.
- There is an exception to this rule however. When your shared object’s value fluctuates very frequently (like stock prices), then it is necessary to synchronize the accessor too, in order to report the correct value of the object rather than some intermediate (and inaccurate) value of the object. There are more advanced techniques to get around making your accessors synchronized which I will show you in the advanced thread tutorial. But for now, be sure to synchronize everything!
No comments:
Post a Comment