Article View: borland.public.jbuilder.java.language
Article #7372Re: HashMap.keySet().iterator() and threads
From: Owen Green
Date: Mon, 25 Jun 2001 09:31
Date: Mon, 25 Jun 2001 09:31
24 lines
1791 bytes
1791 bytes
> while (localStack.keySet().iterator().hasNext()) {
> String fileName=(String)localStack.keySet().iterator().next();
> }
>
> Now, what would happen if somebody else, out of this thread, adds/removes
a
> few lines in localStack while this loop is running. LocalStack is HashMap.
HashMap is not synchronized, so the answer is nothing good (hard to predict,
but without synchronizing access to it, deadlocks (for example) are
definately on the menu). You've got a number of options for getting round
this
1)As suggested in the Javadoc for HashMap, use java.util.Collections to
obtain a synchronized refernece to localStack *which is used for every call
in every thread* (otherwise there's no point doing it...).
2)To acheieve the same result, wrap every call to localStack in
synchonized(){ } blocks.
FYI, check out
http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28460
hth
Owen Green
Technical Details
Message-ID:
<3b3704e5$1_2@dnews>Path:
arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!sn-xit-02!supernews.com!nntp-relay.ihug.net!newsfeeds.ihug.co.nz!ihug.co.nz!dnewsReferences:
<3b36ff40_1@dnews>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,2ab9a045bec56d80 X-Google-Attributes: gidf74b3,public X-Google-ArrivalTime: 2001-06-25 02:32:41 PST From: "Owen Green" <owen@norobots.unique.com> Newsgroups: borland.public.jbuilder.java.language References: <3b36ff40_1@dnews> Subject: Re: HashMap.keySet().iterator() and threads Date: Mon, 25 Jun 2001 10:31:14 +0100 Lines: 26 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 5.50.4133.2400 X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4133.2400 NNTP-Posting-Host: 213.86.7.136 Message-ID: <3b3704e5$1_2@dnews> X-Trace: dnews 993461477 213.86.7.136 (25 Jun 2001 02:31:17 -0700) Path: arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!sn-xit-02!supernews.com!nntp-relay.ihug.net!newsfeeds.ihug.co.nz!ihug.co.nz!dnews