I am using the following code:
public class SomeClass extends Thread {
...
private double a;
private double b;
private double increaseVal;
public void setIncreaseVal(double increaseVal) {
this.increaseVal = increaseVal;
}
private void updateAB() {
...
// Computing the new a and b values
a = ... * increaseVal;
b = ... * increaseVal;
...
}
@Override
public void run() {
try {
...
updateAB();
Thread.sleep(500);
}
...
}
}
public class OtherClass {
...
private HashMap<String, SomeClass> someClasses;
private void setIncreaseValue( String id, double value){
...
someClasses.get(id).setIncreaseValue(value);
...
}
}
Is it possible to lock somehow the increaseVal
in SomeClass
updateAB
method such that when it is processed the same increaseVal
value is employed when both a
and b
fields are updated?
With the current code if setIncreaseValue
from OtherClass
is called it could change the value of increaseVal
after a
is updated. In this manner the new value of increaseVal
will be used when b
is updated. I would like to avoid that.
If I put synchronized(this)
before updating the a
and b
value would it work?
Like this:
synchronized(this) {
// Computing the new a and b values
a = ... * increaseVal;
b = ... * increaseVal;
}
Thanks!