If I have a class, call it X and X contains a collection (assume I am not using one of the synchronized colections, just a normal one).
If I was to write my own method synchronized add()- how does the locking work? Is the locking done on the instance of X, and not on the collection object?
So synchronizing my add() method would not stop many instances of X from calling add() and inserting into the collection- therefore I could still have threading problems?
A synchronized method locks the object. If your
X.addis synchronized, it will prevent concurrent execution of other synchronized methods of the sameXobject. If anyone out of thatXobject has access to the same collection, the collection will not be protected.If you want your collection to be protected, make sure it is not accessible to the rest of the world in any way other than a synchronized method of
X. Also, this is a bit unclear in your question, but note that a synchronized non-static method locks the object. Assuming eachXinstance will have a collection of its own, they won’t interfere with each other.Another option, BTW, is to lock the collection instead of the
Xobject:This will synchronize access to the locked collection instead of the
Xobject. Use whichever you find easier and more effective.