Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Java > Java and JDK > Pro Java
| Search | Today's Posts | Mark Forums Read
Pro Java Expert level Java questions not about a specific book. Please indicate your version.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Pro Java section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old September 22nd, 2006, 05:38 AM
Authorized User
 
Join Date: Dec 2005
Location: Kathmandu, Bagmati, Nepal.
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
Default 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
__________________
http://www.ravishakya.com
  #2 (permalink)  
Old October 9th, 2006, 08:32 PM
Friend of Wrox
 
Join Date: Jan 2006
Location: San Francisco, CA, USA.
Posts: 198
Thanks: 0
Thanked 0 Times in 0 Posts
Default

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/


Similar Threads
Thread Thread Starter Forum Replies Last Post
data integration/sharing cpojoe BOOK: Beginning SharePoint 2007: Building Team Solutions with MOSS 2007 ISBN: 978-0-470-12449-9 4 November 9th, 2008 06:01 AM
Connecting to multiple com ports using threads gaurisharya Beginning VB 6 0 April 8th, 2008 12:01 AM
Accessing data from two threads lmadhavi Visual C++ 1 September 14th, 2004 06:59 AM
Record sharing by multiple users demivolt Access 1 August 26th, 2004 08:17 PM





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