java 向量和线程安全

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1658697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:27:53  来源:igfitidea点击:

java Vector and thread safety

javavectormultithreadingthread-safety

提问by Guy

I'm wondering if this code will do any trouble:

我想知道这段代码会不会有什么问题:

I have a vector that is shared among many threads. Every time a thread has to add/remove stuff from the vector I do it under a synchronizedblock. However, the main thread has a call:

我有一个在许多线程之间共享的向量。每次线程必须从向量中添加/删除内容时,我都会在synchronized块下进行。但是,主线程有一个调用:

System.out.println("the vector's size: "+ vec.size());

which isn't synchronized.

这不是synchronized.

Should this cause trouble?

这应该引起麻烦吗?

回答by jarnbjo

All Vector methods are synchronized themselves, so as long as you are only synchronizing around a single method, your own synchronization is not necessary. If you have several method calls, which depend on each other, e.g. something like vec.get(vec.size()-2)to get the second last element, you have to use your own synchronization since otherwise, the vector may change between vec.size() and vec.get().

所有 Vector 方法本身都是同步的,因此只要您仅围绕单个方法进行同步,您自己的同步就不是必需的。如果您有多个相互依赖的方法调用,例如vec.get(vec.size()-2)获取倒数第二个元素,您必须使用自己的同步,否则,向量可能会在 vec.size() 和 vec.get() 之间发生变化。

回答by finnw

I assume you are referring to java.util.Vector.

我假设您指的是java.util.Vector.

Actually Vector.size()issynchronized and will return a value consistent with the vector's state (when the thread calling size()enters the monitor.) If it returns 42, then at some point in time the vector contained exactly 42 elements.

实际上Vector.size()同步的,并且将返回一个与向量状态一致的值(当线程调用size()进入监视器时)。如果它返回 42,那么在某个时间点向量正好包含 42 个元素。

If you're adding items in a loop in another thread then you cannot predict the exact size, but it should be fine for monitoring purposes.

如果您在另一个线程的循环中添加项目,则您无法预测确切的大小,但对于监视目的来说应该没问题。

回答by Phil Ross

Each of the methods of java.util.Vectoris synchronized, so this won't cause any problems for something that is just logging the size.

java.util.Vectoris 的每个方法synchronized,因此这不会对仅记录大小的内容造成任何问题。

To improve performance you may be better off replacing your Vectorwith an ArrayList. The methods of ArrayListaren't synchronized, so you would need to synchronize all access yourself.

为了提高性能,你可能会关闭免去您更好VectorArrayList。的方法ArrayList不是synchronized,因此您需要自己同步所有访问权限。

回答by Hyman

Mind that you can always obtain a synchronized version of a collection by using Collections.synchronizedCollection(Collection<T> c)static method..

请注意,您始终可以使用Collections.synchronizedCollection(Collection<T> c)静态方法获取集合的同步版本。