简单的问题。以下代码是线程安全的吗?
如果是,还有更好的方法吗?
如果没有,为什么?以及如何使它线程安全。
我的主要疑问是因为ArrayList
内的Hashtable
,因为ArrayList
不是线程安全的。因此,如果Hashtable
的一部分也会发生同样的事情。
Hashtable<Thread, List<String>> threadObjects = new Hashtable<Thread, List<String>>();
// lets assume some object is added.
synchronized (threadObjects)
{
thread = Thread.currentThread();
List<String> v = threadObjects.get(thread);
if (null != v)
{
// do something
}
}
谢谢
最佳答案
如果是,还有更好的方法吗?
是的,但是使用ThreadLocal>
我的主要疑问是因为Hashtable中的ArrayList是因为ArrayList不是线程安全的。
通常您是对的,但是此代码确保ArrayList仅由一个线程访问。当然,如果您不遵循这种模式,那将是线程安全的。
注意:synchronized (threadObjects)
在这种情况下没有任何区别。
关于java - HashTable中的ArrayList是线程安全的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14380523/