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

3

I'm developing a Handle for a stream of data, where events will be periodically released that should be captured by a small set of Listeners from 1 to 5 listeners .

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

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

  • No need to sort
  • The set will be constant (it will not be immutable, but it will not have been constantly changed during execution)
  • It will not be necessary for recurring calls to be obtained in the same order.
  • You will not need to be Thread Safe.
  • The set will be small, initially from 1 to 5% with%.
asked by anonymous 11.08.2015 / 01:50

1 answer

2

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

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

    
11.08.2015 / 08:49