Java Reference
In-Depth Information
Make the state variable immutable ; or
Use synchronization whenever accessing the state variable.
If you haven't considered concurrent access in your class design, some of these approaches
can require significant design modifications, so fixing the problem might not be as trivial as
this advice makes it sound. It is far easier to design a class to be thread-safe than to retrofit
it for thread safety later.
In a large program, identifying whether multiple threads might access a given variable can
be complicated. Fortunately, the same object-oriented techniques that help you write well-
organized, maintainable classes—such as encapsulation and data hiding—can also help you
create thread-safe classes. The less code that has access to a particular variable, the easier it
is to ensure that all of it uses the proper synchronization, and the easier it is to reason about
the conditions under which a given variable might be accessed. The Java language doesn't
force you to encapsulate state—it is perfectly allowable to store state in public fields (even
public static fields) or publish a reference to an otherwise internal object—but the better en-
capsulated your program state, the easier it is to make your program thread-safe and to help
maintainers keep it that way.
When designing thread-safe classes, good object-oriented techniques—encapsulation, im-
mutability, and clear specification of invariants—are your best friends.
There will be times when good object-oriented design techniques are at odds with real-world
requirements; it may be necessary in these cases to compromise the rules of good design for
the sake of performance or for the sake of backward compatibility with legacy code. Some-
times abstraction and encapsulation are at odds with performance—although not nearly as
often as many developers believe—but it is always a good practice first to make your code
right, and then make it fast. Even then, pursue optimization only if your performance meas-
urements and requirements tell you that you must, and if those same measurements tell you
that your optimizations actually made a difference under realistic conditions. [1]
If you decide that you simply must break encapsulation, all is not lost. It is still possible to
make your program thread-safe, it is just a lot harder. Moreover, the thread safety of your
program will be more fragile, increasing not only development cost and risk but maintenance
cost and risk as well. Chapter 4 characterizes the conditions under which it is safe to relax
encapsulation of state variables.
Search WWH ::




Custom Search