|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Thread safety simply means that the fields of an object or class always maintain a valid state, as observed by other objects and classes, even when used concurrently by multiple threads.
One of the first guidelines I proposed in this column (see "Designing object initialization") is that you should design classes such that objects maintain a valid state, from the beginning of their lifetimes to the end. If you follow this advice and create objects whose instance variables all are private and whose methods only make proper state transitions on those instance variables, you're in good shape in a single-threaded environment. But you may get into trouble when more threads come along.
Multiple threads can spell trouble for your object because often, while a method is in the process of executing, the state of your object can be temporarily invalid. When just one thread is invoking the object's methods, only one method at a time will ever be executing, and each method will be allowed to finish before another method is invoked. Thus, in a single-threaded environment, each method will be given a chance to make sure that any temporarily invalid state is changed into a valid state before the method returns.
Once you introduce multiple threads, however, the JVM may interrupt the thread executing one method while the object's instance variables are still in a temporarily invalid state. The JVM could then give a different thread a chance to execute, and that thread could call a method on the same object. All your hard work to make your instance variables private and your methods perform only valid state transformations will not be enough to prevent this second thread from observing the object in an invalid state.
Such an object would not be thread-safe, because in a multithreaded environment, the object could become corrupted or be observed to have an invalid state. A thread-safe object is one that always maintains a valid state, as observed by other classes and objects, even in a multithreaded environment.
There are two big reasons you need to think about thread safety when you design classes and objects in Java:
Because multithreading is built into Java, it is possible that any class you design eventually may be used concurrently by multiple threads. You needn't (and shouldn't) make every class you design thread-safe, because thread safety doesn't come for free. But you should at least think about thread safety every time you design a Java class. You'll find a discussion of the costs of thread safety and guidelines concerning when to make classes thread-safe later in this article.
JVMSimulator and Method.java and search for sychronized. http://www.artima.com/insidejvm/applets/sourcecode.html