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.