Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization on "this" or private Object in Java? [duplicate]

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++;
        }
    }
}
like image 539
AllTooSir Avatar asked Jun 23 '12 06:06

AllTooSir


2 Answers

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.

like image 117
Costi Ciudatu Avatar answered Nov 15 '22 20:11

Costi Ciudatu


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++;
        }
    }
}
like image 33
Kumar Vivek Mitra Avatar answered Nov 15 '22 18:11

Kumar Vivek Mitra