I could not find any definitive answer to my question elsewhere so I'm deciding to ask.
I am having porting code into Java and making it threadsafe. I'm applying as many getters/setters as I can on objects and passing them around. And obviously these values are not set as static. But I'm also looking at other angles.
For any particular thread I want all methods in a class to be able to access a class variable without other threads interfering (and WITHOUT synchronized variable keyword), is the following acceptable?
public class TestClass {
public double testVal;
public void methodA() {
testVal = 22.6;
}
public double methodB() {
return testVal;
}
}
If I create an instance of TestClass
in main
and call methodA
then methodB
on that object, it returns my testVal
. This problem is to be scaled up with many many values shared across different methods in the class as i'm just showing a simple demo.
Is this a good threadsafe approach? This data would be stored on the thread stack rather than the heap if I'm correct?
Cheers