Topic
IC4NOTICE: developerWorks Community will be offline May 29-30, 2015 while we upgrade to the latest version of IBM Connections. For more information, read our upgrade FAQ.
2 replies Latest Post - ‏2005-09-23T11:25:49Z by SystemAdmin
SystemAdmin
SystemAdmin
757 Posts
ACCEPTED ANSWER

Pinned topic Be a good (event) listener - Question.

‏2005-08-16T04:06:51Z |
This is very good article.

I would be thankful if you could answer one query for me. You are suggesting use of CopyOnWriteArrayList class but consider a situation as you have narrated where another thread just unregistered the listener while first thread is iterating through the collection. Now this collection class will make a copy of it but the first thread who is iterating still holds the reference to listener just unregistered. So even if the listener is un-registered it still will get event because the iterating thread still holds copy of list where the listener is still there.

So how this problem the CopyOnWriteArrayList will solve?

Thanks a lot for your time.
Updated on 2005-09-23T11:25:49Z at 2005-09-23T11:25:49Z by SystemAdmin
  • SystemAdmin
    SystemAdmin
    757 Posts
    ACCEPTED ANSWER

    Re: Be a good (event) listener - Question.

    ‏2005-09-16T19:57:55Z  in response to SystemAdmin
    This is true. It is possible that any threads which are currently iterating the list may call a listener slightly after it has been deregistered. Most of the time, this is harmless.

    Note that this is still possible if your listener list is managed even by a non copy-on-write approach. Lets say Thread A is iterating a thread-safe listener list which deals constructively with removal, and calls next(), returning the soon-to-be deregistered listener. Then a context switch occurs, and thread B removes the listener, and continues on. Switch back to A -- it now holds a reference to a deregistered listner, and calls it. SImilarly, the classic technique of cloning the listener list before calling it would have the same vulnerability. Only if you locked the listener list for the entirety of iteration would you be immune to this problem.

    COWAL doesn't introduce the problem, it simply has the same behavior as other approaches. If this is really a problem (most of the time, it isn't) you'd want to either lock the list (potentially compromising concurrency) or code the listeners defensively.