Synchronized ArrayList?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Serge_Novgorodsky
Posted On:   Monday, September 3, 2001 12:33 PM

The article ( http://developer.java.sun.com/developer/onlineTraining/collections/Col lection.html#VectorAndStackClasses) gives an example of using a synchronized ArrayList: lst = Collections.synchronizedList(lst); synchronized (lst) { Iterator iter = lst.iterator(); while (iter.hasNext()) System.out.println(iter.next()); } My question is: If I'm using Vector do I need an explicit synchronized call while iterating too? If not, then isn't Vector easier to use if you need just a thread-safe List? Another question regarding the ArrayList: Should I do something like this - public void    More>>

The article
(
http://developer.java.sun.com/developer/onlineTraining/collections/Col lection.html#VectorAndStackClasses)

gives an example of using a synchronized ArrayList:


			
lst = Collections.synchronizedList(lst);
synchronized (lst) {
Iterator iter = lst.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}


My question is:

If I'm using Vector do I need an explicit synchronized call while iterating too?

If not, then isn't Vector easier to use if you need just a thread-safe List?

Another question regarding the ArrayList:


Should I do something like this -


			
public void foo()
{
//lst is previously allocated
//synchronized ArrayList
synchronized(lst)
{ .....
int size = lst.size();
.....
}
}

if I need to make sure that the size doesn't change in the middle of

foo()?



Thanks in advance,


-Serge

   <<Less

Re: Synchronized ArrayList?

Posted By:   John_Zukowski  
Posted On:   Monday, September 3, 2001 08:06 PM

The source you include is not from the tutorial you mention. At least not on the page you point to. I can't tell what exactly you are asking.


Synchronizing on the collection object does not prevent the collection from changing. In the case of a List synchronized through synchronizedList(), the lock is an internal mutex object.


Iterating through a Vector is not-thread safe.

About | Sitemap | Contact