Suppose I have the following:
public class Foo {
private ReadingList mReadingList = new ReadingList();
public ReadingList getReadingList() {
synchronized (mReadingList) {
return mReadingList;
}
}
}
If I try modifying the ReadingList object in two threads, the synchronization above won’t help me, right?:
// Thread 1
foo1.getReadingList().setName("aaa");
// Thread 2
foo2.getReadingList().setName("bbb");
do I have to wrap each method I want synchronized like so:
public class Foo {
private ReadingList mReadingList = new ReadingList();
public synchronized void setReadingListName(String name) {
mReadingList.setName(name);
}
public synchronized void setReadingListAuthor(String author) {
mReadingList.setAuthor(author);
}
...
and so on for each method of ReadingList I want exposed and synched? I’d end up just writing wrapper methods for each method of ReadingList.
Thanks
1. You have access to the ReadingList source
If you have access to the ReadingList object, add
synchronizedto all of the methods of ReadingList if you desire synchronized access to all of the fields or a certain group of setters if you only wish to interleave access to certain fields.2. You do not have access to ReadingList
You would have to write something like:
3. Use a general purpose lock object
Depending on the nature of Foo and how general-purpose this whole thing is, you may find that only a certain class or classes present the threading issue in ReadingList.
In such a class you could use a general purpose lock object: