list - Java Synchronized Collections vs Object -
i'm wondering difference between these ways of synchronization
list<integer> intlist = collections.synchronizedlist(new arraylist<integer>()); synchronized (intlist) { //stuff }
and using object lock
object objectlock = new object(); list<integer> intlist = new arraylist<integer>(); synchronized (objectlock) { //stuff }
the first approach makes sure individual method calls synchronized, , avoids needing manage separate lock object. 1 thread can call
intlist.add(3);
and can call
intlist.clear();
without synchronized
block, , it'll synchronized. (unfortunately, doesn't when need hold lock group of function calls; then, need synchronized
block around calls.) also, if need pass list around, can use
otherobject.dostuffwith(intlist);
and
return intlist;
instead of
otherobject.dostuffwith(intlist, objectlock);
and
return listandlock(intlist, objectlock);
Comments
Post a Comment