There are basically three approaches you can take to make an object such as
RGBThread
thread-safe: - Synchronize critical sections
- Make it immutable
- Use a thread-safe wrapper
RGBThread
thread-safe: If this class definition were used, e.g. forpublic class AddressData {
private String streetAddress;
private String zipCode;
public AddressData( String streetAddress, String zipCode) {
this.setAddress( streetAddress, zipCode );
....
}
public synchronized void setAddress( String streetAddress,
String zipCode) {
// validity checks
....
// set fields
....
}
public synchronized String getStreetAddress() { // problematic!
return this.streetAddress;
}
public synchronized String getZipCode() { // problematic!
return this.zipCode;
}}
it would in principle be possible to get an inconsistent address. For example, between the calls to address.getStreetAddress() and address.getZipCode(), it is possible that a call to address.setAddress could occur. In this case, getStreetAddress would return the old street address, while getZipCode() would return the new zip code.printMailingLabel( address.getStreetAddress(),
address.getZipCode() );
The SimpleAddressData class can contain just public streetAddress and zipCode fields, without accessors. It is being used solely to return the two objects at the same time.public synchronized SimpleAddressData getAddress() {
return new SimpleAddressData( this.streetAddress,
this.zipCode );
}