[OCP 11 Complete Study Guide] [OCP 11 Programmer I Book] [OCP 11 Programmer II Book] [OCP 11 Practice Tests Book] [OCA 8 Book] [OCP 8 Book] [OCP 8 Practice Tests Book] [Blog]
Originally posted by Scott Selikoff:
My instinct for this is no its not safe and map.values() could get corrupted, although questions like this always kind of made my head spin.
As for performance costs, you can improve concurrency in the getAll() by not sychronizing the entire method, but just the part that reads from the map.
Originally posted by Ronnie Ho:
Ken, thanks for your post. I did intend to make the HashMap private and I carelessly left it out (I just edited the post just now). My question is if I synchronized the add() method, but not the getAll() method, is it going to cost problem? If one thread is putting a new Entry into the map, while another trying to create an ArrayList object with the map.values(), is it going to corrupt the newly created ArrayList object ? Thanks.
Unfortunately, your attempt at improving performance is *not* thread safe. The values() method returns a collection backed by the original map. It too, needs to be synchronized, even during the small period while it is being loaded into the array list.
[OCP 11 Complete Study Guide] [OCP 11 Programmer I Book] [OCP 11 Programmer II Book] [OCP 11 Practice Tests Book] [OCA 8 Book] [OCP 8 Book] [OCP 8 Practice Tests Book] [Blog]
Originally posted by Scott Selikoff:
Hmm, I wasn't sure on this one. I tended to hope calling a method like map.values() would not expose the internal mapping of the set, ergo it is completely independent of the original mapping, but after reading the API, yeah it is backed, good catch.
"I'm not back." - Bill Harding, Twister
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |