Simple question. Is following code is thread safe…?
- If yes, is there is any better way..?
- If no, why.? and how can I make it thread safe.
My main doubt because of ArrayList inside Hashtable because ArrayList is not thread safe. So same thing will happen if its part of 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
}
}
Thanks
Yes, but use a ThreadLocal>
Normally you would be right, however this code ensures that an ArrayList is only accessed by one thread. Of course if you didn’t following this pattern it would be thread safe.
Note: The
synchronized (threadObjects)doesn’t make any difference in this case.