Synchronization on "this" or private Object in Java?

Possible Duplicate:
Avoid synchronized(this) in Java?

What is the difference between the two pieces of code ? What are advantages and disadvantages of each?

1)

public class Example {
private int value = 0;

public int getNextValue() {
    synchronized (this) {
        return value++;
    }
}
}

2)

public class Example {
private int value = 0;

private final Object lock = new Object();

public int getNextValue() {
    synchronized (lock) {
        return value++;
    }
}
}

The main reason why I would choose the 2nd approach is that I do not control what the clients do with the instances of my class.

If, for some reason, somebody decides to use an instance of my class as a lock, they will interfere with the synchronization logic within my class:

class ClientCode {
    Example exampleInstance;

    void someMethod() {
        synchronized (exampleInstance) {
            //...
        }
    }
}

If, within my Example class, I'm using a lock that no one else can see, they cannot interfere with my logic and introduce an arbitrary mutex like in the above scenario.

To sum up, this is just an application of the information hiding principle.


I would prefer the second option if I need to execute two different tasks simultaneously which are independent of each other.

eg:

public class Example {
    private int value = 0;
    private int new_value = 0;
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    public int getNextValue() {
        synchronized (lock1) {
            return value++;
        }
    }

    public int getNextNewValue() {
        synchronized (lock2) {              
            return new_value++;
        }
    }
}

I would say the second method is better. Consider the following situation:

public class Abc{

    private int someVariable;

    public class Xyz {
        //some method,synchronize on this
    }

        //some method, and again synchronize on this


}

In this situation this is not the same in the two methods. One is a method of the inner class. Hence, it is better to use a common object for synchronization. Eg, synchronized (someVariable) .

链接地址: http://www.djcxy.com/p/76256.html

上一篇: java synchronized(this)作用域

下一篇: 在Java中的“this”或私人对象上同步?