Daniel Pitts wrote:
> Mark Space wrote:
>> Knute Johnson wrote:
>>> I have a List that I need to access in two threads, in one thread I
>>> clear, add and get the size of the List. The other just iterates
>>> over the List. To prevent a ConcurrentModificationException, I can't
>>> allow the list to be cleared or elements added when it is being
>>> iterated in the other thread. My question is, will there be any
>>> problem using the size() method unsynchronized in the thread that
>>> clears and adds elements? Visibility shouldn't be a problem because
>>> all the changes to the List occur in that thread.
>>
>> What do you mean "unsynchronized"? Is the List synchronized or do you
>> always synchronize on some common lock?
>>
>> Read-only or not, visibility is always an issue unless the backing
>> variables are declared "volatile". Unless you are certain that you
>> are already synchronizing correctly, I think I'd just go ahead and
>> make the List into the synchronized version. You'll still need to
>> lock the whole thing for iterating over though, or you'll get
>> concurrent modification exceptions.
> I think the OP was saying that the size() method would only be called
> from the thread that did any mutating of the data structure. In which
> case, the happens-before relationship of a single thread will enforce a
> correct result. Ofcourse, if it isn't a standard list, and iterating
> actually changes the structure, all bets are off.
>
> To the OP: Can you give more details about the two threads? Does the
> thread which modifies the list only do it infrequently, and the other
> one inspect the list frequently? Visa versa? Something else?
Hard to quantify infrequently but the two threads could act upon the
List simultaneously so they must be protected. The thread that iterates
over the list does not modify the list.
> If the list is updated infrequently, you might be better off having a
> volatile reference to a list, and have the "writing" thread re-create a
> new (unmodifiable) list with the new data, and place it into that
> volatile reference. In the reading thread, list.iterator() will return
> the iterator of the "most recently set" list, and iterate through that
> until completed, regardless of new lists that come and go.
I ended up using a CopyOnWriteArrayList that creates a separate array
for the iterator. It accomplishes pretty much what you describe.
Thanks,
--
Knute Johnson
email s/nospam/knute2008/
--
Posted via NewsDemon.com - Premium Uncensored Newsgroup Service
------->>>>>>http://www.NewsDemon.com<<<<<<------
Unlimited Access, Anonymous Accounts, Uncensored Broadband Access
|