For an unordered set of listeners what is the best java.util.Set implementation to use?

Asked

Viewed 54 times

3

I’m developing a Handle to a data stream, where periodically events will be launched that are to be captured by a small set of Listeners from 1 to 5 listeners.

This set of listeners do not need to be triggered in registration sequence, it will only be guaranteed that if any excpetion, is made available on log, without interrupting the others.

What is the best implementation of the Interface java.util.Set considering:

  • No need for ordination
  • The set will be constant (it will not be immutable, but it will not undergo constant changes during execution)
  • Recurring calls need not be obtained in the same order
  • No Thread Safe Required.
  • The set will be small, initially from 1 to 5 listeners.
  • Needs to be a Set? For such a small ensemble, a ArrayList + a duplicate check should be good enough... Any other set implementation will likely have a overhead unnecessary in such a small-scale scenario. (which does not mean that it cannot be used, since the difference in performance will be tiny - unless there are many observable objects, each with its own set of listeners - and the convenience of the interface Set can be interesting; in that case I would answer "any one")

  • There is no need to be a Set, the List could also be used, but run the risk of duplicate the set protects me and avoid having to worry about the suggested check.

1 answer

2

Use a CopyOnWriteArraySet. According to the documentation, it is the ideal implementation for cases where "set sizes usually remain small" and "read-only operations are much more frequent than mutant operations". She is also thread-safe, but only writing operations have a overhead associated, the query via iterators is quite fast (which is what you will use most often, i.e. when an event occurs you will scroll through the listeners notifying them of it).

In short, it is basically an implementation of the interface Set via a ArrayList, just as I had suggested in comment, and still maintaining the convenience of the interface Set (plus strategy copy-on-write, for thread-Safety). For small sets that do not change frequently, this implementation will be the best you could achieve, or at least something very close to it.

  • Does not apply to the requirements I have mentioned.

  • @Delfino Which one, and why?

  • No Thread Safe Required.

  • @Delfino "Not necessary" is different from "being forbidden", isn’t it? In my reply I stressed that the most common operation - query via iterators - does not bring any overhead additional (as it does not entail a lock). I maintain my position that this is the most appropriate implementation for your case, but as usual, to be sure just testing...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.