Re: Threads having datamember as HashMap
vivek_12315 wrote:
I am producing a scenario, where say 10 Threads have their 10 private
HashMaps .... And T[i] just modifies its own copy of H[i] .....
I hope this type of model shall work (leaving the argument that
"HashMap is not ThreadSafe"
Right ?
There are thread-safe Maps in the API.
Think in terms of interfaces, really types, and not concrete classes
as you're doing. You need a thread-safe HashMap, you say? Why a
HashMap and not some other Map, then? There are two easy ones:
'Collections.synchronizedMap( someMap )' and
'java.util.concurrent.ConcurrentHashMap'. They support different
degrees of thread safety.
<http://download.oracle.com/javase/6/docs/api/java/util/
Collections.html#synchronizedMap(java.util.Map)>
<http://download.oracle.com/javase/6/docs/api/java/util/concurrent/
ConcurrentHashMap.html>
The easiest thread safety is not to share data, as you stated in your
post. Local variables tend to be thread-isolated, as for example:
public void foo()
{
Map <Foo, Bar> map = new HashMap <Foo, Bar> ();
// use 'map' without exposing it to any other threads
}
'ThreadLocal' is effective but trickier.
<http://download.oracle.com/javase/6/docs/api/java/lang/
ThreadLocal.html>
Its purpose is to make data "globally" available "locally" to a
thread, loosely speaking, that is, to have a thread-contained
reference with wider scope or longer lifetime than a local variable.
Personally I avoid 'ThreadLocal' references, perhaps foolishly.
Immutable references to immutable instances are thread-safe as long as
their initialization /happens-before/ any thread's attempt to read
them.
Robert Klemme wrote:
If you are interested in the topic I recommend Doug Lea's book.
Also Brian Goetz's, et al. Mr. Goetz is also a frequent writer on
concurrency topics in IBM Developerworks and other places.
--
Lew