It really depends on what you are trying to protect but I think in your example, neither approach is going to work because it is the static values within IntProvider that need synchronization. In other words, something like this should work:
public IntProvider {
private static int value = 0;
public static void setValue(int newValue) {
synchronized(IntProvider.class){
value = newValue;
}
}
public static int getValue() {
synchronized(IntProvider.class){
return value;
}
}
This would keep any
thread regardless of the code it was executing from at the time from modifying the 'value' reference while another thread was either changing or accessing it.
To answer the original question though about the difference between
class versus
instance synchronization, the answer is that there is really no difference.
Synchronization is done on an object,
1.) usually "this" as in the synchronized keyword used in an instance method,
2.) sometimes the Class instance representing a class (as in the above example) and
3.) sometimes on an Object instance created just for the purpose of synchronization.
For example of the last case, the following would be
functionally equivalent to the previous example:
public IntProvider {
private static int value = 0;
private static Object synchObject = new Object();
public static void setValue(int newValue) {
synchronized(synchObject){
value = newValue;
}
}
public static int getValue() {
synchronized(synchObject){
return value;
}
}
HTH