Synchronizing access to an inner object's methods?
Posted
by
user291701
on Stack Overflow
See other posts from Stack Overflow
or by user291701
Published on 2012-06-30T14:58:17Z
Indexed on
2012/06/30
15:16 UTC
Read the original article
Hit count: 207
java
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
© Stack Overflow or respective owner