简体   繁体   中英

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?

没错,但是doJob将在实例级别同步,因此可以在两个或更多个类A的两个实例上同时由两个或多个不同的线程同时执行doJob方法。如果希望doJob仅由一个线程在以下位置执行时间(例如,因为它破坏了静态字段),您应该将其声明为静态,或者使用静态字段作为锁定对象来同步整个方法主体。

鉴于您正在尝试使用非静态(即每个对象一个)监视器来保护静态(即每个类一个)字段,我想说“一次仅一个线程将执行该方法,而其他线程将继续执行该方法。等待”声明不成立。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM