2

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?

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
  • If another thread changes the variable the getY() method needs to b e synchronized to that change in another thread. – brso05 Nov 21 '14 at 15:54
  • Thread1 - changes y using setY() Thread2 - access y using getY() needs to be able to see change that Thread1 made. – brso05 Nov 21 '14 at 15:56

0 Answers0