简体   繁体   中英

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 . 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.

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.

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.

This is a reason monitor objects and synchronised blocks are preferred way.

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