Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
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
Page 6 of 7
Here's an immutable version of RGBColor:
// In file threads/ex3/RGBColor.java
// Instances of this immutable class
// are thread-safe.
public class RGBColor {
private final int r;
private final int g;
private final int b;
public RGBColor(int r, int g, int b) {
checkRGBVals(r, g, b);
this.r = r;
this.g = g;
this.b = b;
}
/**
* returns color in an array of three ints: R, G, and B
*/
public int[] getColor() {
int[] retVal = new int[3];
retVal[0] = r;
retVal[1] = g;
retVal[2] = b;
return retVal;
}
public RGBColor invert() {
RGBColor retVal = new RGBColor(255 - r,
255 - g, 255 - b);
return retVal;
}
private static void checkRGBVals(int r, int g, int b) {
if (r < 0 || r > 255 || g < 0 || g > 255 ||
b < 0 || b > 255) {
throw new IllegalArgumentException();
}
}
}
Note that the setColor() method is simply removed, as it doesn't make sense in an immutable RGBColor object. The getColor() method, which reads the instance variables, is identical to what it has been, except now it doesn't have to be synchronized.
The invert() method, which writes to the instance variables, is changed. Instead of inverting the current object's color, this new invert() creates a new RGBColor object that represents the inverse of the object upon which invert() is invoked, and returns a reference to that object.
JVMSimulator and Method.java and search for sychronized. http://www.artima.com/insidejvm/applets/sourcecode.html