(Revised after some further thought)
For the example presented above you can get away with declaring your static int as volatile as punkers suggested.
In the general-case however - for example if your static variable were an object with mutable state ...
The synchronized instance method means that only the thread holding the object-instance lock is allowed to progress in that method of that instance of class A, and that when the thread finishes in the method and releases the lock any other thread entering any synchronized block using the same lock will "see" the changes you made.
It does not prevent changes being made to the static variable by another thread which:
- assigns a new value to the static variable directly from outside class A (the variable is public!)
- calls a static method of class A (synchronized or otherwise) which reassigns the static variable, because it will use a different lock
- calls a non-synchronized instance method of class A
Using synchronized methods is generally a bit dangerous - they can lead to deadlocks because the lock can be taken externally by other code which uses your class/instance as the target of a synchronized block:
synchronized (objectOfTypeA) { ... } // takes the instance lock
or
synchronized (A.getClass()) { ... } // takes the class lock
A better approach might be to make the static variable private, add a private local variable to use as a lock (so it cannot be locked externally), and use the private local lock in synchronized blocks in your methods:
public class A {
private static int reg_no = 100;
private Object lock = new Object();
public void registration(){
synchronized(lock) {
reg_no = some operation...
}
}
public static int getRegNo() {
synchronized(lock) {
return reg_no;
}
}
}