开发者

Utility for registering and notifying listeners?

I've used various kinds of listeners over the years. Recently read the concurrency chapter in Josh Bloch's Effective Java where he talks about synchronizing adding and removing listeners, but recommends instead using CopyOnWriteArrayList/Set.

Recently I've used JMX MBean notifications. JMX provides a base class that you can extend, NotificationBroadcasterSupport, which provides the relevant methods for you: addNotificationListener, removeNotificationListener, sendNotification. In addition to the default constructor, there's one that takes an Exexutor which provides an easy way to make notifying listeners asynchronous. And presumably, this class internally uses something like CopyOnWriteArrayList internally to avoid synchronization issues (e.g. if listeners tries to remove itself from the list as part of its handleNotification method).

This makes me wonder if there are any general utilities for doing this.开发者_如何学Go If I need a mechanism for registering and notifying listeners (that doesn't involve JMX), rather than roll my own using CopyOnWriteArrayList and possibly Executors and such, it would be good if there was a packaged, tested utility. Does anything like this exist in the JDK or common utility libs like Google's?


Yes, You can do this using Observer design pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜