问题
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 final Object lock = new Object();
private int value = 0;
public int getNextValue() {
synchronized (lock) {
return value++;
}
}
}
回答1:
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.
回答2:
I would prefer the second option if I need to execute two different tasks simultaneously which are independent of each other.
e.g.:
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++;
}
}
}
回答3:
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. E.g., synchronized (someVariable)
.
回答4:
I think it really depends on the situation. Lets say your class is a subclass and the super class has a method that has synchronization. And lets say you are working with the same data set and want to maintain integrity within your method as well. Then definitely approach 1 is what you should be using.
Otherwise second approach would work better based on what Costi mentioned
来源:https://stackoverflow.com/questions/11167566/synchronization-on-this-or-private-object-in-java