synchronizedCollection 和 contains——我需要手动同步吗?
我在 Java 中使用 Collections.synchronizedCollection 来保护我知道多个线程同时访问的 Set。 Java API 警告:
“用户在迭代返回的集合时必须手动同步它:
Collection c = Collections.synchronizedCollection(myCollection);
...
synchronized(c) {
Iterator i = c.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}
”
如果我使用 c.contains(obj)
,那是线程安全的吗?显然,在内部,这是迭代 Collection 并查看其中是否有任何对象等于 obj。我的直觉是假设这可能是同步的(如果不是,这似乎是一个重大失败),但考虑到之前同步的痛苦,仔细检查似乎是明智的,谷歌搜索对此的答案还没有转向任何东西。
I'm using Collections.synchronizedCollection in Java to protect a Set that I know is getting accessed concurrently by many threads. The Java API warns:
" It is imperative that the user manually synchronize on the returned collection when iterating over it:
Collection c = Collections.synchronizedCollection(myCollection);
...
synchronized(c) {
Iterator i = c.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}
"
If I use c.contains(obj)
, is that thread-safe? Internally, obviously, this is iterating over the Collection and seeing if any of the objects in it are equal to obj. My instinct is to assume that this is probably synchronized (it would seem to be a major failing if not), but given previous pains with synchronization, it seems wise to double-check, and a Google search for answers on this hasn't turned up anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就其本身而言,对
contains
的调用是安全的。问题在于,人们经常测试集合是否包含某个元素,然后根据结果对集合执行某些操作。
最有可能的是,测试和操作应该被视为单个原子操作。在这种情况下,应该获得集合上的锁,并且这两个操作都应该在
synchronized
块中执行。In itself, a call to
contains
is safe.The problem is that one often tests whether a collection contains an element then does something to the collection based on the result.
Most likely, the test and the action should be treated as a single, atomic operation. In that case, a lock on the collection should be obtained, and both operations should be performed in the
synchronized
block.Collections.synchronizedCollection()
将返回一个线程安全
集合,这意味着任何单个方法调用本身都是线程安全的。这取决于你想做什么。如果你想调用几个方法,java 不能使其线程安全。
Collections.synchronizedCollection()
will return athread safe
collection which meansany single method call is
thread safe
by itself. It depends what you want do. If you want to call couple of methods, java cannot make it thread safe together.它是安全的,因为
contains
本身是同步的。It's safe, because
contains
itself is synchronized.