Subject: Sharing a data structure across multiple threads
Posted By: ravishakya Post Date: 9/22/2006 5:38:19 AM
Hi, I would like to share a data structure (e.g. HashMap) across multiple threads. Each thread will be adding an entry to the HashMap. A part of the code is:
HashMap info = new HashMap();
File[] contents = mainDir.listFiles();

for (int i = 0; i < contents.length; i++) {           
                    spawnThread st = new spawnThread(contents[i], info);
                                        Thread t = new Thread(st);
                    t.start();
 }


How can I get it done properly?


http://www.ravishakya.com
Reply By: panacea Reply Date: 10/9/2006 8:32:32 PM
It looks like you've already passed the info HashMap to the new thread, so therefore the parent thread and the child thread should both have access to it.  However, HashMaps are not thread-safe.  Therefore you should have a synchronized() block around any code that does gets or sets on the HashMap.  

E.g.:

synchronized(info)
{
    info.put("Foo", new Boolean(true));
}

synchronized(info)
{
    boolean foo = ((Boolean)info.get("Foo")).booleanValue();
}


Jon Emerson
http://www.jonemerson.net/

Go to topic 50240

Return to index page 153
Return to index page 152
Return to index page 151
Return to index page 150
Return to index page 149
Return to index page 148
Return to index page 147
Return to index page 146
Return to index page 145
Return to index page 144