mdev
mdev

Reputation: 472

Java Threads and synchronization

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?

Upvotes: 0

Views: 104

Answers (4)

silijon
silijon

Reputation: 942

yes, you're outline is correct. and it does technically bottleneck the system while the other threads wait for access. and this is perfectly fine and normal as long as you avoid putting any heavy processing or i/o within the synchronized block.

Upvotes: 0

SJuan76
SJuan76

Reputation: 24885

No.

Marking an instance method as synchronized means the same that doing

public void myMethod() {
  synchronized(this) {
    ...
  }
}

So, you can only guarantee that two threads are not running the same method of the same object. The same method from another object can be run simultaneously.

Try to synchronize with a more "static" object. I would use the class object itself, or some static (and inmutable) member.

Upvotes: 0

tibtof
tibtof

Reputation: 7957

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.

Upvotes: 1

alf
alf

Reputation: 8513

Given that you're trying to guard static (i.e. one per class) fields with non-static (i.e. one per object) monitors, I would say that the "only one thread at a time will be executing the method and the others will keep waiting" claim does not hold.

Upvotes: 0

Related Questions