In this approach to making an object thread-safe, you don't mark critical sections as synchronized. Instead, you separate out the critical sections that read instance variables from those that write to instance variables. The critical sections that read are left as-is. The critical sections that write must be changed so that, instead of altering the current object's instance variables, they create a new object that embodies the new state and returns a reference to that object.
String
and the primitive type wrappers such as Integer
, Long
, Float
, Boolean
, Character
, and so on.It also lets you pass references to them to methods without worrying that the method will change the object's state. In addition, if the overhead of immutability (excessive creation of short-lived objects) may at times be too inefficient, you can also define a mutable companion class that can be used when the immutable version isn't appropriate. An example of this design approach in the Java API is the StringBuffer
class, which serves as a mutable companion to the immutable String
class. Note that the StringBuffer
class is also thread-safe, but it uses the "normal" approach: its instance variables are private and its critical sections are synchronized.
No comments:
Post a Comment