I have a web app that uses some jars written by me.
My challenge is that i have a critical (but fast) section in my code.
1 – I have an object of a given class that has a couple of static fields. Let’s call this class A
2 _ A exposes a not static method that access the static fields. for reading and writting. Lets call this method doJob.
3 – Every request instantiates an object of the class A and calls doJob.
A a = new A(); a.doJob();
4 – I assume that every request is creating a new Thread where doJob is executed.
5 – If I define doJob as public synchronized void doJob () {//Do the job} only one Thread at a time will be executing the method and the others will keep waiting.
The question is: Is it all right what i am saying?
You are right, but doJob will be synchronized at instance level, so doJob method could be executed in the same time by two or more different threads on two or more instances of class A. If you want doJob to be executed only by one thread at a time (e.g because it chages static fields) you should either declare it static or synchronize the whole method body using a static field as locking object.