简体   繁体   English

带有私有不可变对象的同步块和同步方法的区别

[英]Synchronized block with private immutable object and synchronize method difference

private final Object lockObject = new Object();
public void getCount() {
    synchronized( lockObject ) {
        ...
    }
}

Why above code is better than below one: 为什么上面的代码比下面的代码更好:

public void synchronized getCount() {
      ...
}

I searched and found explanation as mentioned below. 我搜索并找到了如下所述的解释。

Putting it on the method means you are using the lock of the object itself to provide thread safety. 将其放在方法上意味着您正在使用对象本身的锁来提供线程安全。 With this kind of mechanism, it is possible for a malicious user of your code to also obtain the lock on your object, and hold it forever, effectively blocking other threads. 通过这种机制,恶意代码用户也可能获得对象上的锁,并将其永久持有,从而有效地阻塞了其他线程。 A non-malicious user can effectively do the same thing inadvertently. 非恶意用户可以无意中有效地执行相同的操作。

But i couldn't understand this completely. 但是我无法完全理解这一点。 How a mallicious user can hold a lock for ever? 恶意用户如何永久持有锁? Can any one give an explanation with a sample code, to justify above scenario? 任何人都可以用示例代码进行解释,以证明上述情况是正确的吗?

With

public class Example {
    public void synchronized getCount() {
            ...
    }
}

it's synchronizing on current object this . 它正在当前对象上同步this Other class is able to get the reference of current object and use it as monitor lock: 其他类能够获取当前对象的引用并将其用作监视器锁定:

public class OtherClass {

    public void otherMethod() {
        Example example = new Example();
        synchronized (example) {
            ...
        }
    }
}

This might get unexpected results, for example, causing getCount blocked when otherMethod being executed. 这可能会得到意外的结果,例如,导致在执行otherMethod时阻塞了getCount

With the first approach, since the monitor lock lockObject is private, other class is not able to access it directly, so it's preferred over the second approach. 在第一种方法中,由于监视器锁lockObject是私有的,因此其他类无法直接访问它,因此它比第二种方法更可取。

To put in simple words - 简而言之-

When you use locking at method level you are getting lock of object of complete class in which you have synchronised method. 在方法级别使用锁定时,您将获得已同步方法的完整类对象的锁定。

Suppose if any user comes with some shiny code to execute method till universe ends .. this will result in other threads getting blocked for using other methods in your class. 假设是否有任何用户带有一些闪亮的代码来执行方法直到Universe结束..这将导致其他线程因使用类中的其他方法而被阻塞。

This is a reason monitor objects and synchronised blocks are preferred way. 这是首选监视对象和同步块的原因。

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

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