If I am using synchronized, then does the object which is being synchronized have to be static?
EDIT:
I meant to say reference to objects must be static. I noticed that one of the examples I was reading stated that in order for threads to use a synchronized method in class A, then the reference to class A must be static.
So, I was wondering whether it is a rule to make the reference to an object static, so that all the threads which call the synchronized method are using the same copy of instance. In my example, the synchronized method is used to count from 1 to 10. So each thread accessing this synchronized method should each count 1 to 10. I tried this without static and the results were incorrect.
At the risk of over-trivializing this:
Examine code and identify the set of resources, or data that will be accessed by code that will be running on concurrent threads. The code to consider may span multiple methods, possibly classes.
In general, synchronize on something representative of the set of resources:
If the set of resources are all object instance data (non static), then it’s acceptable to synchronize on the object owning the data. (If that object isn’t ‘this’, be asking yourself many questions!).
If any portion of the set of resources is static class data, then you must synchronize on something representative of the static data. This might be the
classitself. (Also know that primitive values aren’t objects).ALWAY lock on the same thing for any given set of resources. This ensures that threads competing for the same set of resources are coordinating properly with each other.
If you are considering two such sets of resources, there must not be any one item that belongs to both sets. If such were the case, they must become one single set of resources.
If you have methods in the same object that are NOT competing (read or write) for anything from the set of resources identified in (1), then that method may not need to be synchronized. HOWEVER, if the method will be used concurrently then consider that:
If such a method does access data from another set of resources, then it will need to be synchronized to that set.
See (3).
Read this to understand how the
sychronizedkeyword works for static vs instance methods