0

I've searched there're 3 types of synchronizing function calls inside a class, I've listed them below.

Just being curious, what's the core differences between SyncCollection1, SyncCollection2, SyncCollection3, any potential issues in any of them?

class SyncCollection1 { // using synchronized in function signature
    List<Integer> list = new ArrayList();
    public synchronized void add(int o) {
        list.add(o);
    }
    public synchronized void remove(int o) {
        list.remove(o);
    }
}
class SyncCollection2 { // using synchronized(this) inside function
    List<Integer> list = new ArrayList();
    public void add(int o) {
        synchronized (this) {
            list.add(o);
        }
    }
    public void remove(int o) {
        synchronized (this) {
            list.remove(o);
        }
    }
}
class SyncCollection3 { // using ReentrantLock lock()/unlock()
    List<Integer> list = new ArrayList();
    Lock reentrantLock = new ReentrantLock();
    public void add(int o) {
        reentrantLock.lock();
        list.add(o);
        reentrantLock.unlock();
    }
    public void remove(int o) {
        reentrantLock.lock();
        list.remove(o);
        reentrantLock.unlock();
    }
}

(1) What's the core difference between putting "synchronized" as function signature, and "synchronized(this)" for the whole function body?

(2) In what scenario a function level "lock" is better than a function level "synchronized(this)"?

Thanks a lot.

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119
  • 1) for the code you've shown, basically nothing is different. They're basically the same thing. 2) The lock here is private, and cannot be accessed by another class. That can be good or bad, depending. – markspace Jan 08 '19 at 06:25
  • Further on (2), I'd only use ReentrantLock if you need the extra facilities it offers (eg reporting on wait queue lengths, etc), since the lock is guaranteed to be released if an exception occurs with the 'synchronized' options. In SyncCollection3, if the add or remove fail, then the lock will be left stuck locking - too easy to forget to add the extra boilerplate of a 'finally' clause. – racraman Jan 08 '19 at 07:02

0 Answers0