Why is synchronized block better than synchronized method?

后端 未结 10 984
Happy的楠姐
Happy的楠姐 2020-12-07 08:05

I have started learning synchronization in threading.

Synchronized method:

public class Counter {

   private static int count = 0;

   public stati         


        
10条回答
  •  忘掉有多难
    2020-12-07 08:33

    Although not usually a concern, from a security perspective, it is better to use synchronized on a private object, rather than putting it on a method.

    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.

    If you use the lock of a private data member, you can prevent this, since it is impossible for a malicious user to obtain the lock on your private object.

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

    This technique is mentioned in Bloch's Effective Java (2nd Ed), Item #70

提交回复
热议问题