Threadsafe access to ArrayList

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?UGhpbA==?=

    #1

    Threadsafe access to ArrayList

    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
  • Ignacio Machin ( .NET/ C# MVP )

    #2
    Re: Threadsafe access to ArrayList

    On May 14, 9:19 am, Phil <phi...@sbcglob al.netwrote:
    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.

    Comment

    • Ashutosh Bhawasinka

      #3
      Re: Threadsafe access to ArrayList

      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(ArraySyncO bject)
      {
      //add entryies here
      }
      }
      -----------

      thread2:
      while(...)
      {
      lock(ArraySyncO bject)
      {
      //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

      lock
      Phil wrote:
      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

      Comment

      Working...