Share
Explore BrainMass

Making a Java Class Thread Safe

The following class

public class HardwareData
{
private boolean value = false;

public HardwareData(boolean value) {
this.value = value;
}

public boolean get() {
return value;
}

public void set(boolean newValue) {
value = newValue;
}

public boolean getAndSet(boolean newValue) {
boolean oldValue = this.get();
this.set(newValue);

return oldValue;
}

public void swap(HardwareData other) {
boolean temp = this.get();

this.set(other.get());
other.set(temp);
}
}

abstracts the idea of the get-and-set and swap instructions. However, this class is not considered safe, because multiple threads may concurrently access its methods and thread safety requires that each method be performed atomically. Rewrite the HardwareData class using Java synchronization so that it is thread safe.

Solution Preview

A simple rewrite of given Java code to make it thread safe is to make every method atomic by adding the keyword synchronized in method declaration or just declare the needed code block as synchronized.

public class HardwareData
{
private boolean value = false;

public HardwareData(boolean value) {
synchronized (this) {
this.value = value;
}
}

public ...

Solution Summary

Response provides two different ways of achieving thread safety in the given Java class.

$2.19