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++;
}
}
}
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.
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++;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With