Is arraylist threadsafe?

A

archana

Hi all,

I am having one arraylist which i want to share accross threads.

What i am doing is traversing through element of arraylist in both the
thread. Means just reading element of that arraylist.

So my question is do i need to use lock while traversing. As i am not
updating inserting or deleing any element of arraylust, so i think it
should not ask for locking.

Please help me asap.

thanks in advance.
 
J

Jon Skeet [C# MVP]

I am having one arraylist which i want to share accross threads.

What i am doing is traversing through element of arraylist in both the
thread. Means just reading element of that arraylist.

That should be fine. If you were writing to the list, you'd have to
lock in all threads. Just for reading, you're okay.

Jon
 
B

Ben Voigt [C++ MVP]

Jon Skeet said:
That should be fine. If you were writing to the list, you'd have to
lock in all threads. Just for reading, you're okay.

Although, if you aren't writing (and specifically if you aren't inserting or
removing), then an array will be even better than ArrayList.
 
A

Arnshea

Hi all,

I am having one arraylist which i want to share accross threads.

What i am doing is traversing through element of arraylist in both the
thread. Means just reading element of that arraylist.

So my question is do i need to use lock while traversing. As i am not
updating inserting or deleing any element of arraylust, so i think it
should not ask for locking.

Please help me asap.

thanks in advance.

I would synchronize access while traversing the arraylist. You may
not need to modify the arraylist now but you, or someone else, might
need to in the future. Is a single thread populating the array? If
you use a lock you'll be able to make sure that the readers wait until
the ArrayList is filled before reading.

If the performance impact of synchronizing access to the arraylist is
too high then consider using a ReaderWriterLock. Since all of your
threads are readers they will be able to access the arraylist
concurrently.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Arnshea said:
I would synchronize access while traversing the arraylist. You may
not need to modify the arraylist now but you, or someone else, might
need to in the future. Is a single thread populating the array? If
you use a lock you'll be able to make sure that the readers wait until
the ArrayList is filled before reading.

If the performance impact of synchronizing access to the arraylist is
too high then consider using a ReaderWriterLock. Since all of your
threads are readers they will be able to access the arraylist
concurrently.

In cases where you only read from the list there is no need for sync.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top