java - synchronizedList access by multiple threads -
i have basic question synchronizedlist
.
lets have synchronizedlist -
list synclist = collections.synchronizedlist(new arraylist<>())
now scenario thread trying access add()
api , thread b trying access remove()
api of synchronizedlist. both thread able access both(add , remove) api @ same time.
i believe threads should not access api(add() , remove()) same time. please correct me if wrong.
will both thread able access both(add , remove) api @ same time.
the answer no.
if chance @ collections.synchronizedlist(list)
source code, see that, method creating instance of static inner class named synchronizedlist
or synchronizedrandomaccesslist
, depending on type of list
send argument.
now both these static inner class extend common class called synchronizedcollection
, maintains mutex
object, on method operations synchronize on
this mutex
object assigned this
, means that, mutex
object same returned instance.
since add()
, remove()
methods performed under
synchronized(mutex) { }
block, thread executes add
(and aquires lock on mutex
), not allow another thread execute remove
(by aquiring lock on same mutex
), since former has already locked mutex
. latter thread wait until lock obtained former thread on mutex
gets released.
so, yes add()
, remove()
mutually exclusive
Comments
Post a Comment