I'm trying to make sure I understand the performance implications of synchronized in java. I have a couple of simple classes:
public class ClassOne {
private ClassTwo classTwo = new ClassTwo();
public synchronized void setClassTwo(int val1, int val2) {
classTwo.setVal(val1);
classTwo.setVal2(val2);
}
public static void main(String[] args) {
ClassOne classOne = new ClassOne();
classOne.setClassTwo(10, 100);
}
}
public class ClassTwo {
private int val;
private int val2;
public synchronized void setVal(int val) {
this.val = val;
}
public synchronized void setVal2(int val2) {
this.val2 = val2;
}
}
So, as you can see in the previous example, I'm synchronizing on ClassOne.setClassTwo and ClassTwo.setVal and ClassTwo.setVal2. What I'm wondering is if the performance is exactly the same if I remove the synchronization on ClassTwo.setVal and ClassTwo.setVal2, like so:
public class ClassTwo {
private int val;
private int val2;
public void setVal(int val) {
this.val = val;
}
public void setVal2(int val2) {
this.val2 = val2;
}
}
They are functionally equivalent in this scenario (assuming no other classes are using these classes), but wondering how much overhead (if any) there is in having more synchronization.