Purchase Solution

Making a Java Class Thread Safe

Not what you're looking for?

Ask Custom Question

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.

Purchase this Solution

Solution Summary

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

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 ...

Purchase this Solution


Free BrainMass Quizzes
Geometry - Real Life Application Problems

Understanding of how geometry applies to in real-world contexts

Know Your Linear Equations

Each question is a choice-summary multiple choice question that will present you with a linear equation and then make 4 statements about that equation. You must determine which of the 4 statements are true (if any) in regards to the equation.

Solving quadratic inequalities

This quiz test you on how well you are familiar with solving quadratic inequalities.

Probability Quiz

Some questions on probability

Multiplying Complex Numbers

This is a short quiz to check your understanding of multiplication of complex numbers in rectangular form.