Suppose you have an API you’ve written that collects data in real time in an independent thread. Data access is thread-safe and via an interface. E.g. getData() which does not block and provides the latest information. This API is used in a number of applications; some GUI driven, others console programs.
What options do you have to notify your application that there has been a data update? We definitely do not want the API to depend on the application, so we do not want to fireTableDataChanged() or anything like that from the API. (In our GUI application, we would call fireTableDataChanged() etc. after the API notifies us or we look at the API.)
Thanks much!
One option is to write your own event producer class.
IEventListener is implemented by the observers. It has a method for receiving an event.
IEventProducer is implemented by any observable, via EventProducer. It has methods for adding and removing listeners.
EventProducer is thread-safe. It has a method for sending events to a CopyOnWriteArrayList of listeners. It catches and logs any exceptions thrown by listeners. It also provides methods for adding and removing listeners.
Then, any observable class can implement IEventProducer via an internal EventProducer.
If you try to support two listener types on the same class, type erasure will require that you name the add/remove listener methods differently for the different listeners.