The Artima Developer Community
Sponsored Link

Java Answers Forum
Synchronization and collections

2 replies on 1 page. Most recent reply: Apr 3, 2002 5:39 AM by Singh M.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Singh M.

Posts: 154
Nickname: ms
Registered: Mar, 2002

Synchronization and collections Posted: Apr 1, 2002 11:57 PM
Reply to this message Reply
Advertisement
I have a synchronized list, obtained as follows :

List list = Collections.synchronizedList(new ArrayList());

my query is whether looping over the list..

for (int i =0; i < list.size(); i++)
{
some other processing...
}

will be thread safe or not?


Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Synchronization and collections Posted: Apr 2, 2002 1:15 AM
Reply to this message Reply
As long as all access to the list is through the synchronized list that was returned, it should be thread safe. Note that in addition to what you have, you need to put the code that is using the list in a synchronized block. It is pretty easy to write a little test of this "theory" by making a simple program with several threads that fool around with the plain list and then the synchronized version of it.

By the way, why do you not use an Iterator to iterate through the list? That for-loop stuff on the List's size() is so twentieth century! Here is how I would do your example:
List list = Collections.synchronizedList( someListOfStuff );
synchronized(list)
{
    Iterator it = list.iterator();
    while(it.hasNext())
    {
        MyObject mo = (MyObject)it.next();
 
        // ...some incredibly fascinating processing...
    }
}

Singh M.

Posts: 154
Nickname: ms
Registered: Mar, 2002

Re: Synchronization and collections Posted: Apr 3, 2002 5:39 AM
Reply to this message Reply
Thanks for the suggestion.

Flat View: This topic has 2 replies on 1 page
Topic: Java to load XML doc using DOM Previous Topic   Next Topic Topic: image

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use