java - Synchronized keyword- how it works? -


if have class, call x , x contains collection (assume not using 1 of synchronized colections, normal one).

if write own method synchronized add()- how locking work? locking done on instance of x, , not on collection object?

so synchronizing add() method not stop many instances of x calling add() , inserting collection- therefore still have threading problems?

a synchronized method locks object. if x.add synchronized, prevent concurrent execution of other synchronized methods of same x object. if out of x object has access same collection, collection not protected.

if want collection protected, make sure not accessible rest of world in way other synchronized method of x. also, bit unclear in question, note synchronized non-static method locks object. assuming each x instance have collection of own, won't interfere each other.

another option, btw, lock collection instead of x object:

void add(object o) {    synchronized(mycollection) {       mycollection.add(o);    } } 

this synchronize access locked collection instead of x object. use whichever find easier , more effective.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -