From page 231 of OCP Java SE 6 Programmer Practice Exams, question 56:
public class Buffalo {
protected int y;
public int getY() { return y; }
public void setY(int newY) { y = newY; }
}
Which methods need to be synchronized to make the class thread safe?
And the book says that the correct answer is - all of them:
Even methods that don't change a variable's value need to be synchronized if they accessed the variable.
Why I need to synchronize getY()
?
It's not changing the state, so it can't cause any synchronization problems, isn't it?