简单的问题。以下代码是线程安全的吗...?
- 如果是的话,有没有更好的方法..?
- 如果没有,为什么?以及如何使其线程安全。
我的主要疑问是 Hashtable
内的 ArrayList
因为 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
}
}
谢谢
最佳答案
If yes, is there is any better way..?
是的,但是使用ThreadLocal>
My main doubt because of ArrayList inside Hashtable because ArrayList is not thread safe.
通常情况下你是对的,但是这段代码确保 ArrayList 只能由一个线程访问。当然,如果您不遵循此模式,它将是线程安全的。
注意:在这种情况下,synchronized (threadObjects)
没有任何区别。
关于java - HashTable 中的 ArrayList 是线程安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14380523/