简体   繁体   English

锁定Java类中静态成员的获取

[英]Lock acquistion on static members within a Java Class

I am currently resolving a performance degradation issue due to heavy lock contention. 我目前正在解决由于锁争用过多而导致的性能下降问题。 I am considering "Lock splitting" to resolve this issue. 我正在考虑使用“锁拆分”来解决此问题。

The skeletal usage pattern is :: 骨骼使用模式为::

CURRENT USAGE :: 当前用法::

public class HelloWorld{

   public static synchronized method1(){
       //uses resource 1
   }
   public static synchronized method2(){
        //uses resource 2
   }

}

MY APPROACH :: 我的方法::

since method1() and method2() does not use the same resource, I am thinking of splitting the locks. 由于method1()method2()没有使用相同的资源,因此我正在考虑拆分锁。 As of now, they both contend for the Class lock since they are both static synchronized. 到目前为止,由于它们都是静态同步的,因此它们都争用了Class锁。 I am thinking of changing it to :: 我正在考虑将其更改为::

public class HelloWorld{

   **private static Object resr1Lock = new Object();**

   public static method1(){
       synchronized(resrc1Lock){
            //uses resource 1
       }
   }

   **private static Object resr2Lock = new Object();** 
   public static method2(){
        synchronized(resrc2Lock){
             //uses resource 2
        }
   }

}

Will they now contend for the "Class Lock" or resr1Lock / resrc2Lock ? 他们现在会争夺“ Class Lock”还是resr1Lock / resrc2Lock

他们现在将争用2个对象“ resr1Lock” /“ resrc2Lock。它将按您期望的那样工作。

他们不会再争夺对Class对象的锁定,因此可以解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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