I am curios about something to do with Java Method Synchronization and Object locking.
When you invoke a synchronized method, from what i understand it locks the entire object for the duration of the method call.
Does this mean you only need to synchronize methods that write data to your object and not for the reading of data from your object?
public class testclass {
private ArrayList<String> data;
public ArrayList<String> getData() {
return data;
}
public synchronized void setData(ArrayList<String> data) {
this.data = data;
}
}
Basically would the above code be thread safe (Since the testclass object is locked while running the setData method)? or should i also synchronize the getData method as well?
No – if you don’t synchronize the reads, you don’t have any visibility guarantee (you could get a stale version of the object).
Note: in your case, you don’t need to use the synchronized keyword because each method is atomic – you could simply make
datavolatile instead.