import java.awt.Dimension; /* * Goal: maintain a fixed ratio between length and width. * This version is thread-safe */ public class ThreadSafeAspectRatio { // Get rid of the AtomicIntegers; thread-safety is now // provided with synchronized blocks private int length = 0; private int width = 0; public ThreadSafeAspectRatio(int l,int w) { this.length = l; this.width = w; } // use a synchronized block to ensure that the length and // width are set atomically public synchronized void setLength(int newLength) { double ratio = ((double)length) / width; length = newLength; width = (int) ((double) newLength / ratio); } // To preserve the aspect ratio invariant, we must return // the length and width together public synchronized Dimension getDimension() { return new Dimension (length,width); } }