synchronizedList access by multiple threads

java, multithreading

Solution

Will the Both thread able to access the Both(add and remove) api at the same time.

The answer is no.

If you get a chance to look at `Collections.synchronizedList(List)` source code, you see that, the method is creating the instance of a static inner class named `SynchronizedList` or `SynchronizedRandomAccessList`, depending on the type of `List` you send as argument.

Now both these static inner class extend a common class called `SynchronizedCollection`, which maintains a `mutex` object, on which all method operations synchronize on

This `mutex` object is assigned with `this`, which essentially means that, the `mutex` object is the same returned instance.

Since the `add()` and `remove()` methods are performed under the

synchronized(mutex) {

}

block, a thread which executes `add` (and aquires lock on `mutex`), will not allow another thread to execute `remove` (by aquiring lock on same `mutex`), since the former has already locked the `mutex`. The latter thread will wait until the lock obtained by former thread on `mutex` gets released.

So, yes `add()` and `remove()` are mutually exclusive

Problem

I have very basic question about the `SynchronizedList`. Lets say I have synchronizedList as - ``` List syncList = Collections.synchronizedList(new ArrayList<>()) ``` Now my scenario is Thread A is trying to access `add()` api and Thread B trying to access `remove()` api of synchronizedList. Will the Both thread able to access the Both(add and remove) api at the same time. I believe the threads should not access the api(add() and remove()) same time. Please correct me if I am wrong.

Original source