但我正在同步这个名单'对象到处都是新的。怎么样?
违规代码:
public Roster getRoster() {
if (roster == null) {
return null;
}
if (!roster.rosterInitialized) {
try {
synchronized (roster) {
roster.reload();
long waitTime = SmackConfiguration.getPacketReplyTimeout();
long start = System.currentTimeMillis();
while (!roster.rosterInitialized) {
if (waitTime <= 0) {
break;
}
roster.wait(waitTime);
long now = System.currentTimeMillis();
waitTime -= now - start;
start = now;
}
}
}
catch (InterruptedException ie) {
// Ignore.
}
}
return roster;
}
答案 0 :(得分:8)
“获取新内容”是指您创建新名单对象?
您确定要正确同步吗?同步发生在实例上,而不发生在变量上。所以,如果你这样做。
synchronized(roster) {
roster = new Roster();
// do something
}
然后您只同步到旧,而不是新 roster
。
因此以下代码应该产生相同的错误:
Roster roster = new Roster();
Roster othervariable = roster;
synchronized(othervariable) {
roster = new Roster(); // create a new roster
othervariable.wait(1000); // OK, since synchronized with this instance!
roster.wait(1000); // NOT OK, not synchronized with *new* roster!
}
变量的名称不会发生同步,而是内容。如果覆盖内容,则不会重新同步到新值!