ArrayList, null and Threads

  • Thread starter Thread starter vooose
  • Start date Start date
V

vooose

Consider a class, ClassA that is used to perform a task using multiple
threads...ie

ClassA aObj = new ClassA(param1);
Thread t = new Thread(new ThreadStart(aObj.DoStuff));
anArrayList.Add(aObj);

The above may be called in many places, so the size of anArrayList
grows.

Now suppose the last two lines of DoStuff are:

anArrayList[0].toString();
anArrayList.Remove(this);

The Error? Sometimes I get ArrayIndexOutOfBounds on anArrayList[0] which
I would have thought was impossible given that an object is only ever
removed from ArrayList BEFORE it is null. Also as I am using
Remove(this) I would have thought that Remove( ) can't get confused
about removing the wrong index.

What I had to do to seemingly fix this was lock access to the arraylist
when calling Add( ) or Remove( ), just a step I didnt understand. Does
anyone know why?
 
ArrayList isn't threadsafe, therefore you should use a threadsafe wrapper
which is returned by calling:

ArrayList.Synchronized(ArrayList list);
 
cody, Thanks for your reply.

Suppose you want a thread-safe ArrayList, as a class variable, you would
then use

private ArrayList myArr = ArrayList.Synchronized(new ArrayList());

?


Not sure why it just isnt synchronized to begin with.

I still can't figure out, even with all the threads in the world
accessing a non-synchronized arraylist, how it could set a member of the
arraylist to null using only Add( ) and Remove(this). Maybe just not
worth wondering about.
 
I still can't figure out, even with all the threads in the world
accessing a non-synchronized arraylist, how it could set a member of the
arraylist to null using only Add( ) and Remove(this). Maybe just not
worth wondering about.


Multiple threads writing in the same object can have unexpected and
undefined results so it maybe really isn't worth to think about which kind
of undefined results there might be.
 
Back
Top