我如何正确同步?
public void consumeResponse(OmwListResponse<T> response) {
synchronized (response.getResultList()) { // XXX this isn't synchronized safely
for (T t : response.getResultList()) {
if (!cacheList.contains(t)) {
cacheList.add(t);
}
}
}
}
情况是我不希望任何人有机会 response.getResultList() 或 cacheList 直到此方法完成。我该如何正确地做到这一点?
public void consumeResponse(OmwListResponse<T> response) {
synchronized (response.getResultList()) { // XXX this isn't synchronized safely
for (T t : response.getResultList()) {
if (!cacheList.contains(t)) {
cacheList.add(t);
}
}
}
}
The the situation is I don't want anyone to chance response.getResultList() or cacheList until this method is done. How do I properly do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建一个锁对象:
并对其进行同步。
Create a lock object:
and synchronize on that.
同步cacheList很容易。只需将使用它的任何代码包装在其中即可:
如果 cacheList 是公共成员,并且您担心外部类会更改它,请将其设为私有成员并同步 getter 和 setter。这是唯一的方法,因为您无法控制其他类的行为,并且您有责任同步您的成员。
至于响应,这比较棘手,因为我不知道 OmwListResponse 是什么。你拥有那个班级吗?如果是这样,请使用与上述相同的方法。如果没有,你可能就不走运了。
Synchronizing cacheList is easy. Just wrap any code your code that uses it in:
If cacheList is a public member and you're afraid external classes will change it, make it a private member and synchronize the getter and setter. This is the only way since you have no control over what other classes do and it is your responsibility to synchronize your members.
As for response, that is trickier because I don't what an OmwListResponse is. Do you own that class? If so, use the same method as above. If not, you may be out of luck.