Threadsafe access to ArrayList

P

Phil

I have two threads that access an ArrayList.

One thread will store new entries. The other thread will retrieve the
entries and then remove them from the list. Is this a thread-safe operation
or do I need to use the Synchronization system?

Thanks,

Phil
 
I

Ignacio Machin ( .NET/ C# MVP )

I have two threads that access an ArrayList.

One thread will store new entries.  The other thread will retrieve the
entries and then remove them from the list.  Is this a thread-safe operation
or do I need to use the Synchronization system?

Thanks,

Phil

Hi,

No, it's not.
You should use a Queue (or Stack) instead of an ArrayList. Queue has
a Synchronizedn method that you can use to make it thread safe.
 
A

Ashutosh Bhawasinka

There is an alternative,
you can create a global(which is accessible to both threads)
synchronization object which can simply be an variable of type Object

Then in each thread use this

//global or class level
Object ArraySyncObject;

thread1:

while(...)
{
lock(ArraySyncObject)
{
//add entryies here
}
}
-----------

thread2:
while(...)
{
lock(ArraySyncObject)
{
//retreive entries
//remove entries
}
}

This is just an alternative. So, make sure that you don't do much
processing in the lock block, as this will block the other thread from
execution.

Regards,
Ashutosh Bhawasinka
 

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