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

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -