The Artima Developer Community
Sponsored Link

Designing for Thread Safety
Using Synchronization, Immutable Objects, and Thread-Safe Wrappers
by Bill Venners
First Published in JavaWorld, July 1998

<<  Page 7 of 11  >>

Advertisement

Approach 3: Thread-safe wrappers
The third approach to making an object thread-safe is to embed that object in a thread-safe wrapper object. In this approach you leave the original class (which isn't thread-safe) unchanged and create a separate class that is thread-safe. Instances of the new class serve as thread-safe "front ends" to instances of the original class.

SafeRGBColor: A thread-safe wrapper
Here's an example of this approach applied to the very first version of RGBColor presented in this article.

// In file threads/ex1/SafeRGBColor.java
// Instances of this class are thread-safe
// wrappers of RGBColor objects, which are
// not thread-safe.
public class SafeRGBColor {

    private RGBColor color;

    public SafeRGBColor(int r, int g, int b) {

        color = new RGBColor(r, g, b);
    }

    public synchronized void setColor(int r, int g, int b) {

        color.setColor(r, g, b);
    }

    /**
    * returns color in an array of three ints: R, G, and B
    */
    public synchronized int[] getColor() {

        return color.getColor();
    }

    public synchronized void invert() {

        color.invert();
    }
}

<<  Page 7 of 11  >>




Google
  Web Artima.com   
Copyright © 1996-2018 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use