Explore BrainMass
Share

Making a Java Class Thread Safe

This content was STOLEN from BrainMass.com - View the original, and get the already-completed solution here!

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.

© BrainMass Inc. brainmass.com October 25, 2018, 3:37 am ad1c9bdddf
https://brainmass.com/math/boolean-algebra/making-a-java-class-thread-safe-347344

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
See Also This Related BrainMass Solution

Java Programming/Mortgage

Please help me create a GUI with 3 JTextField (one for loan amount, one for term, and one for interest rate), one JTextArea (where the monthly payment schedule will be displayed; appended for each month, for all moths; attach a JScrollPane to the JTextArea), one JComboBox (with 3 selections: 7 year at 5.35%, 15 year at 5.5 %, 30 year at 5.75%), and 3 JButton (one for computing the monthly payment schedule, one for resetting all fields, and one for exit the application). The user should be able to input in the text fields the loan amount, interest rate, and term, or input the loan amount in a text field and then select from the combo box the type of loan.

View Full Posting Details