p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   Pro Java (http://p2p.wrox.com/forumdisplay.php?f=200)
-   -   Sharing a data structure across multiple threads (http://p2p.wrox.com/showthread.php?t=48163)

ravishakya September 22nd, 2006 05:38 AM

Sharing a data structure across multiple threads
 
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:
Code:

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

panacea October 9th, 2006 08: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/


All times are GMT -4. The time now is 08:34 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.