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:

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);

How can I get it done properly?


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.


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

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

Jon Emerson

All times are GMT -4. The time now is 04:45 PM.

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