我正在尝试从多个类中的多个方法同步对 xml 文件的读写操作。为了实现这一点,我使用类级别锁来同步此操作。
代码示例:
测试1.java:
public class Test1 {
public void method1() {
synchronized(CommonUtility.class) {
SomeObject someObject = testDAO.readSomething();
.
.
.
testDAO.writeSomething(someObject);
}
}
}
Test2.java
public class Test2 {
public void method2() {
synchronized(CommonUtility.class) {
SomeObject someObject = testDAO.readSomething();
.
.
.
testDAO.writeSomething(someObject);
}
}
}
要实现此类级别的锁定,请考虑以下示例代码:
synchronized(CommonUtility.class) {
.
.
.
}
使用 Object.class 而不是 CommonUtility.class 有什么影响,例如:
synchronized(Object.class) {
.
.
.
}
最佳答案
我认为这两种方法都不理想。
首先这个here建议:
You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class.
换句话说:当您使用 synchronized(CommonUtility.class)
时,您会隐式与 CommonUtility 中的所有静态 synchronized
方法“同步” 。更糟糕的是:想象一下该类今天没有这样的方法。但下周,有人在该实用程序类中添加了这样一个静态同步方法,假设只有对该方法的调用才会通过该监视器。最坏的情况,这可能会导致一些丑陋的(仅限运行时)意外。
然后:追求更广泛的范围(通过使用 Object.class)会让事情变得更糟。
我的答案:首先避免使用类对象。
关于java - 在synchronized block 中使用Object.class锁有什么影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57179801/