Class ThreadSafeEventService

  • Direct Known Subclasses:
    DefaultEventBus

    public class ThreadSafeEventService
    extends Object
    A thread-safe EventService implementation.

    Multithreading

    This implementation is not Swing thread-safe. If publication occurs on a thread other than the Swing EventDispatchThread, subscribers will receive the event on the calling thread, and not the EDT. Swing components should use the SwingEventService instead, which is the implementation used by the EventBus.

    Two threads may be accessing the ThreadSafeEventService at the same time, one unsubscribing a listener for topic "A" and the other publishing on topic "A". If the unsubscribing thread gets the lock first, then it is unsubscribed, end of story. If the publisher gets the lock first, then a snapshot copy of the current subscribers is made during the publication, the lock is released and the subscribers are called. Between the time the lock is released and the time that the listener is called, the unsubscribing thread can unsubscribe, resulting in an unsubscribed object receiving notification of the event after it was unsubscribed (but just once).

    On event publication, subscribers are called in the order in which they subscribed.

    Events and/or topic data can be cached, but are not by default. To cache events or topic data, call setDefaultCacheSizePerClassOrTopic(int), setCacheSizeForEventClass(Class, int), or setCacheSizeForTopic(String, int), setCacheSizeForTopic(Pattern, int). Retrieve cached values with getLastEvent(Class), getLastTopicData(String), getCachedEvents(Class), or getCachedTopicData(String). Using caching while subscribing is most likely to make sense only if you subscribe and publish on the same thread (so caching is very useful for Swing applications since both happen on the EDT in a single-threaded manner). In multithreaded applications, you never know if your subscriber has handled an event while it was being subscribed (before the subscribe() method returned) that is newer or older than the retrieved cached value (taken before or after subscribe() respectively).

    Logging

    All logging goes through the Logger. The Logger is configurable and supports multiple logging systems.

    Exceptions are logged by default, override handleException(String,Object,String,Object,Throwable, StackTraceElement[],String) to handleException exceptions in another way. Each call to a subscriber is wrapped in a try block to ensure one listener does not interfere with another.

    Cleanup of Stale WeakReferences and Stale Annotation Proxies

    The EventService may need to clean up stale WeakReferences and ProxySubscribers created for EventBus annotations. (Aside: EventBus Annotations are handled by the creation of proxies to the annotated objects. Since the annotations create weak references by default, annotation proxies must held strongly by the EventService, otherwise the proxy is garbage collected.) When a WeakReference's referent or an ProxySubscriber's proxiedObject (the annotated object) is claimed by the garbage collector, the EventService still holds onto the actual WeakReference or ProxySubscriber subscribed to the EventService (which are pretty tiny).

    There are two ways that these stale WeakReferences and ProxySubscribers are cleaned up.

    1. On every publish, subscribe and unsubscribe, every subscriber and veto subscriber to a class or topic is checked to see if it is a stale WeakReference or a stale ProxySubscriber (one whose getProxySubscriber() returns null). If the subscriber is stale, it is unsubscribed from the EventService immediately. If it is a ProxySubscriber, it's proxyUnsubscribed() method is called after it is unsubscribed. (This isn't as expensive as it sounds, since checks to avoid double subscription is necessary anyway).
    2. Another cleanup thread may get started to clean up remaining stale subscribers. This cleanup thread only comes into play for subscribers to topic or classes that haven't been used (published/subscribed/unsibscribed to). A detailed description of the cleanup thread follows.

    The Cleanup Thread

    If a topic or class is never published to again, WeakReferences and ProxySubscribers can be left behind if they are not cleaned up. To prevent loitering stale subscribers, the ThreadSafeEventService may periodically run through all the EventSubscribers and VetoSubscribers for all topics and classes and clean up stale proxies. Proxies for Annotations that have a ReferenceStrength.STRONG are never cleaned up in normal usage. (By specifying ReferenceStrength.STRONG, the programmer is buying into unsubscribing annotated objects themselves. There is one caveat: If getProxiedSubscriber() returns null, even for a ProxySubscriber with a STRONG reference strength, that proxy is cleaned up as it is assumed it is stale or just wrong. This would not occur normally in EventBus usage, but only if someone is implementing their own custom ProxySubscriber and/or AnnotationProcessor.)

    Cleanup is pretty rare in general. Not only are stale subscribers cleaned up with regular usage, stale subscribers on abandoned topics and classes do not take up a lot of memory, hence, they are allowed to build up to a certain degree. Cleanup does not occur until the number of WeakReferences and SubscriptionsProxy's with WeakReference strength subscribed to an EventService for all the EventService's subscriptions in total exceed the cleanupStartThreshhold, which is set to CLEANUP_START_THRESHOLD_DEFAULT (500) by default. The default is overridable in the constructor or via #setCleanupStartThreshhold(Integer). If set to null, cleanup will never start.

    Once the cleanup start threshold is exceeded, a java.util.Timer is started to clean up stale subscribers periodically in another thread. The timer will fire every cleanupPeriodMS milliseconds, which is set to the CLEANUP_PERIOD_MS_DEFAULT (20 minutes) by default. The default is overridable in the constructor or via #setCleanupPeriodMS(Integer). If set to null, cleanup will not start. This is implemented with a java.util.Timer, so Timer's warnings apply - setting this too low will cause cleanups to bunch up and hog the cleanup thread.

    After a cleanup cycle completes, if the number of stale subscribers falls at or below the cleanupStopThreshhold cleanup stops until the cleanupStartThreshhold is exceeded again. The cleanupStopThreshhold is set to CLEANUP_STOP_THRESHOLD_DEFAULT (100) by default. The default is overridable in the constructor or via #setCleanupStopThreshhold(Integer). If set to null or 0, cleanup will not stop if it is ever started.

    All cleanup parameters are tunable "live" and checked after each subscription and after each cleanup cycle. To make cleanup never run, set cleanupStartThreshhold to Integer.MAX_VALUE and cleanupPeriodMS to null. To get cleanup to run continuously, set set cleanupStartThreshhold to 0 and cleanupPeriodMS to some reasonable value, perhaps 1000 (1 second) or so (not recommended, cleanup is conducted with regular usage and the cleanup thread is rarely created or invoked).

    Cleanup is not run in a daemon thread, and thus will not stop the JVM from exiting.

    Author:
    Michael Bushe michael@bushe.com
    See Also:
    for a complete description of the API
    • Field Detail

      • CLEANUP_START_THRESHOLD_DEFAULT

        public static final Integer CLEANUP_START_THRESHOLD_DEFAULT
      • CLEANUP_STOP_THRESHOLD_DEFAULT

        public static final Integer CLEANUP_STOP_THRESHOLD_DEFAULT
      • CLEANUP_PERIOD_MS_DEFAULT

        public static final Long CLEANUP_PERIOD_MS_DEFAULT
      • LOG

        protected static final org.scijava.event.bushe.Logger LOG
    • Constructor Detail

      • ThreadSafeEventService

        public ThreadSafeEventService()
        Creates a ThreadSafeEventService that does not monitor timing of handlers.
      • ThreadSafeEventService

        public ThreadSafeEventService​(Long timeThresholdForEventTimingEventPublication)
        Creates a ThreadSafeEventService while providing time monitoring options.
        Parameters:
        timeThresholdForEventTimingEventPublication - the longest time a subscriber should spend handling an event, The service will publish an SubscriberTimingEvent after listener processing if the time was exceeded. If null, no EventSubscriberTimingEvent will be issued.
      • ThreadSafeEventService

        public ThreadSafeEventService​(Integer cleanupStartThreshold,
                                      Integer cleanupStopThreshold,
                                      Long cleanupPeriodMS)
        Creates a ThreadSafeEventService while providing proxy cleanup customization. Proxies are used with Annotations.
        Parameters:
        cleanupStartThreshold - see class javadoc.
        cleanupStopThreshold - see class javadoc.
        cleanupPeriodMS - see class javadoc.
      • ThreadSafeEventService

        public ThreadSafeEventService​(Long timeThresholdForEventTimingEventPublication,
                                      Integer cleanupStartThreshold,
                                      Integer cleanupStopThreshold,
                                      Long cleanupPeriodMS)
        Creates a ThreadSafeEventService while providing time monitoring options.
        Parameters:
        timeThresholdForEventTimingEventPublication - the longest time a subscriber should spend handling an event. The service will publish an SubscriberTimingEvent after listener processing if the time was exceeded. If null, no SubscriberTimingEvent will be issued.
        cleanupStartThreshold - see class javadoc.
        cleanupStopThreshold - see class javadoc.
        cleanupPeriodMS - see class javadoc.
    • Method Detail

      • getCleanupStartThreshhold

        public Integer getCleanupStartThreshhold()
        Gets the threshold above which cleanup starts. See the class javadoc on cleanup.
        Returns:
        the threshold at which cleanup starts
      • setCleanupStartThreshhold

        public void setCleanupStartThreshhold​(Integer cleanupStartThreshhold)
        Sets the threshold above which cleanup starts. See the class javadoc on cleanup.
        Parameters:
        cleanupStartThreshhold - threshold at which cleanup starts
      • getCleanupStopThreshold

        public Integer getCleanupStopThreshold()
        Gets the threshold below which cleanup stops. See the class javadoc on cleanup.
        Returns:
        threshold at which cleanup stops (it may start again)
      • setCleanupStopThreshold

        public void setCleanupStopThreshold​(Integer cleanupStopThreshold)
        Sets the threshold below which cleanup stops. See the class javadoc on cleanup.
        Parameters:
        cleanupStopThreshold - threshold at which cleanup stops (it may start again).
      • getCleanupPeriodMS

        public Long getCleanupPeriodMS()
        Get the cleanup interval. See the class javadoc on cleanup.
        Returns:
        interval in milliseconds between cleanup runs.
      • setCleanupPeriodMS

        public void setCleanupPeriodMS​(Long cleanupPeriodMS)
        Sets the cleanup interval. See the class javadoc on cleanup.
        Parameters:
        cleanupPeriodMS - interval in milliseconds between cleanup runs. Passing null stops cleanup.
      • subscribe

        public boolean subscribe​(Class cl,
                                 EventSubscriber eh)
        See Also:
        EventService.subscribe(Class,EventSubscriber)
      • subscribe

        public boolean subscribe​(Type type,
                                 EventSubscriber eh)
        See Also:
        EventService.subscribe(java.lang.reflect.Type, EventSubscriber)
      • subscribeExactly

        public boolean subscribeExactly​(Class cl,
                                        EventSubscriber eh)
        See Also:
        EventService.subscribeExactly(Class,EventSubscriber)
      • subscribe

        public boolean subscribe​(String topic,
                                 org.scijava.event.bushe.EventTopicSubscriber eh)
        See Also:
        EventService.subscribe(String,EventTopicSubscriber)
      • subscribe

        public boolean subscribe​(Pattern pat,
                                 org.scijava.event.bushe.EventTopicSubscriber eh)
        See Also:
        EventService.subscribe(Pattern,EventTopicSubscriber)
      • subscribeStrongly

        public boolean subscribeStrongly​(Class cl,
                                         EventSubscriber eh)
        See Also:
        EventService.subscribeStrongly(Class,EventSubscriber)
      • subscribeExactlyStrongly

        public boolean subscribeExactlyStrongly​(Class cl,
                                                EventSubscriber eh)
        See Also:
        EventService.subscribeExactlyStrongly(Class,EventSubscriber)
      • subscribeStrongly

        public boolean subscribeStrongly​(String name,
                                         org.scijava.event.bushe.EventTopicSubscriber eh)
        See Also:
        EventService.subscribeStrongly(String,EventTopicSubscriber)
      • subscribeStrongly

        public boolean subscribeStrongly​(Pattern pat,
                                         org.scijava.event.bushe.EventTopicSubscriber eh)
        See Also:
        EventService.subscribeStrongly(Pattern,EventTopicSubscriber)
      • clearAllSubscribers

        public void clearAllSubscribers()
        See Also:
        EventService.clearAllSubscribers()
      • subscribeVetoListener

        public boolean subscribeVetoListener​(Class eventClass,
                                             org.scijava.event.bushe.VetoEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListener(Class,VetoEventListener)
      • subscribeVetoListenerExactly

        public boolean subscribeVetoListenerExactly​(Class eventClass,
                                                    org.scijava.event.bushe.VetoEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListenerExactly(Class,VetoEventListener)
      • subscribeVetoListener

        public boolean subscribeVetoListener​(String topic,
                                             org.scijava.event.bushe.VetoTopicEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListener(String,VetoTopicEventListener)
      • subscribeVetoListener

        public boolean subscribeVetoListener​(Pattern topicPattern,
                                             org.scijava.event.bushe.VetoTopicEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListener(Pattern,VetoTopicEventListener)
      • subscribeVetoListenerStrongly

        public boolean subscribeVetoListenerStrongly​(Class eventClass,
                                                     org.scijava.event.bushe.VetoEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListenerStrongly(Class,VetoEventListener)
      • subscribeVetoListenerExactlyStrongly

        public boolean subscribeVetoListenerExactlyStrongly​(Class eventClass,
                                                            org.scijava.event.bushe.VetoEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListenerExactlyStrongly(Class,VetoEventListener)
      • subscribeVetoListenerStrongly

        public boolean subscribeVetoListenerStrongly​(String topic,
                                                     org.scijava.event.bushe.VetoTopicEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListenerStrongly(String,VetoTopicEventListener)
      • subscribeVetoListenerStrongly

        public boolean subscribeVetoListenerStrongly​(Pattern topicPattern,
                                                     org.scijava.event.bushe.VetoTopicEventListener vetoListener)
        See Also:
        EventService.subscribeVetoListenerStrongly(Pattern,VetoTopicEventListener)
      • subscribeVetoListener

        protected boolean subscribeVetoListener​(Object subscription,
                                                Map vetoListenerMap,
                                                Object vetoListener)
        All veto subscriptions methods call this method. Extending classes only have to override this method to subscribe all veto subscriptions.
        Parameters:
        subscription - the topic, Pattern, or event class to subscribe to
        vetoListenerMap - the internal map of veto listeners to use (by topic of class)
        vetoListener - the veto listener to subscribe, may be a VetoEventListener or a WeakReference to one
        Returns:
        boolean if the veto listener is subscribed (was not subscribed).
        Throws:
        IllegalArgumentException - if vl or o is null
      • subscribe

        protected boolean subscribe​(Object classTopicOrPatternWrapper,
                                    Map<Object,​Object> subscriberMap,
                                    Object subscriber)
        All subscribe methods call this method, including veto subscriptions. Extending classes only have to override this method to subscribe all subscriber subscriptions.

        Overriding this method is only for the adventurous. This basically gives you just enough rope to hang yourself.

        Parameters:
        classTopicOrPatternWrapper - the topic String, event Class, or PatternWrapper to subscribe to
        subscriberMap - the internal map of subscribers to use (by topic or class)
        subscriber - the EventSubscriber or EventTopicSubscriber to subscribe, or a WeakReference to either
        Returns:
        boolean if the subscriber is subscribed (was not subscribed).
        Throws:
        IllegalArgumentException - if subscriber or topicOrClass is null
      • unsubscribe

        public boolean unsubscribe​(Class cl,
                                   EventSubscriber eh)
        See Also:
        EventService.unsubscribe(Class,EventSubscriber)
      • unsubscribeExactly

        public boolean unsubscribeExactly​(Class cl,
                                          EventSubscriber eh)
        See Also:
        EventService.unsubscribeExactly(Class,EventSubscriber)
      • unsubscribe

        public boolean unsubscribe​(String name,
                                   org.scijava.event.bushe.EventTopicSubscriber eh)
        See Also:
        EventService.unsubscribe(String,EventTopicSubscriber)
      • unsubscribe

        public boolean unsubscribe​(Pattern topicPattern,
                                   org.scijava.event.bushe.EventTopicSubscriber eh)
        See Also:
        EventService.unsubscribe(String,EventTopicSubscriber)
      • unsubscribe

        public boolean unsubscribe​(Class eventClass,
                                   Object subscribedByProxy)
        See Also:
        EventService.unsubscribe(Class,Object)
      • unsubscribeExactly

        public boolean unsubscribeExactly​(Class eventClass,
                                          Object subscribedByProxy)
        See Also:
        EventService.unsubscribeExactly(Class,Object)
      • unsubscribe

        public boolean unsubscribe​(String topic,
                                   Object subscribedByProxy)
        See Also:
        EventService.unsubscribe(String,Object)
      • unsubscribe

        public boolean unsubscribe​(Pattern pattern,
                                   Object subscribedByProxy)
        See Also:
        EventService.unsubscribe(java.util.regex.Pattern,Object)
      • unsubscribe

        protected boolean unsubscribe​(Object o,
                                      Map subscriberMap,
                                      Object subscriber)
        All event subscriber unsubscriptions call this method. Extending classes only have to override this method to subscribe all subscriber unsubscriptions.
        Parameters:
        o - the topic or event class to unsubscribe from
        subscriberMap - the map of subscribers to use (by topic of class)
        subscriber - the subscriber to unsubscribe, either an EventSubscriber or an EventTopicSubscriber, or a WeakReference to either
        Returns:
        boolean if the subscriber is unsubscribed (was subscribed).
      • unsubscribeVeto

        public boolean unsubscribeVeto​(Class eventClass,
                                       Object subscribedByProxy)
        See Also:
        EventService.unsubscribeVeto(Class,Object)
      • unsubscribeVetoExactly

        public boolean unsubscribeVetoExactly​(Class eventClass,
                                              Object subscribedByProxy)
        See Also:
        EventService.unsubscribeVetoExactly(Class,Object)
      • unsubscribeVeto

        public boolean unsubscribeVeto​(String topic,
                                       Object subscribedByProxy)
        See Also:
        EventService.unsubscribeVeto(String,Object)
      • unsubscribeVeto

        public boolean unsubscribeVeto​(Pattern pattern,
                                       Object subscribedByProxy)
        See Also:
        EventService.unsubscribeVeto(java.util.regex.Pattern,Object)
      • unsubscribeVetoListener

        public boolean unsubscribeVetoListener​(Class eventClass,
                                               org.scijava.event.bushe.VetoEventListener vetoListener)
        See Also:
        EventService.unsubscribeVetoListener(Class,VetoEventListener)
      • unsubscribeVetoListenerExactly

        public boolean unsubscribeVetoListenerExactly​(Class eventClass,
                                                      org.scijava.event.bushe.VetoEventListener vetoListener)
        See Also:
        EventService.unsubscribeVetoListenerExactly(Class,VetoEventListener)
      • unsubscribeVetoListener

        public boolean unsubscribeVetoListener​(String topic,
                                               org.scijava.event.bushe.VetoTopicEventListener vetoListener)
        See Also:
        EventService.unsubscribeVetoListener(String,VetoTopicEventListener)
      • unsubscribeVetoListener

        public boolean unsubscribeVetoListener​(Pattern topicPattern,
                                               org.scijava.event.bushe.VetoTopicEventListener vetoListener)
        See Also:
        EventService.unsubscribeVetoListener(Pattern,VetoTopicEventListener)
      • unsubscribeVetoListener

        protected boolean unsubscribeVetoListener​(Object o,
                                                  Map vetoListenerMap,
                                                  Object vl)
        All veto unsubscriptions methods call this method. Extending classes only have to override this method to subscribe all veto unsubscriptions.
        Parameters:
        o - the topic or event class to unsubscribe from
        vetoListenerMap - the map of veto listeners to use (by topic or class)
        vl - the veto listener to unsubscribe, or a WeakReference to one
        Returns:
        boolean if the veto listener is unsubscribed (was subscribed).
      • publish

        public void publish​(Object event)
        See Also:
        EventService.publish(Object)
      • publish

        public void publish​(Type genericType,
                            Object event)
        See Also:
        EventService.publish(java.lang.reflect.Type, Object)
      • publish

        public void publish​(String topicName,
                            Object eventObj)
        See Also:
        EventService.publish(String,Object)
      • publish

        protected void publish​(Object event,
                               String topic,
                               Object eventObj,
                               List subscribers,
                               List vetoSubscribers,
                               StackTraceElement[] callingStack)
        All publish methods call this method. Extending classes only have to override this method to handle all publishing cases.
        Parameters:
        event - the event to publish, null if publishing on a topic
        topic - if publishing on a topic, the topic to publish on, else null
        eventObj - if publishing on a topic, the eventObj to publish, else null
        subscribers - the subscribers to publish to - must be a snapshot copy
        vetoSubscribers - the veto subscribers to publish to - must be a snapshot copy.
        callingStack - the stack that called this publication, helpful for reporting errors on other threads
        Throws:
        IllegalArgumentException - if eh or o is null
      • setStatus

        protected void setStatus​(org.scijava.event.bushe.PublicationStatus status,
                                 Object event,
                                 String topic,
                                 Object eventObj)
        Called during publication to set the status on an event. Can be used by subclasses to be notified when an event transitions from one state to another. Implementers are required to call setPublicationStatus
        Parameters:
        status - the status to set on the object
        event - the event being published, will be null if topic is not null
        topic - the topic eventObj is being published on, will be null if event is not null
        eventObj - the payload being published on the topic , will be null if event is not null
      • addEventToCache

        protected void addEventToCache​(Object event,
                                       String topic,
                                       Object eventObj)
        Adds an event to the event cache, if appropriate. This method is called just before publication to listeners, after the event passes any veto listeners.

        Using protected visibility to open the caching to other implementations.

        Parameters:
        event - the event about to be published, null if topic is non-null
        topic - the topic about to be published to, null if the event is non-null
        eventObj - the eventObj about to be published on a topic, null if the event is non-null
      • getSubscribers

        public <T> List<T> getSubscribers​(Class<T> eventClass)
        See Also:
        EventService.getSubscribers(Class)
      • getSubscribersToClass

        public <T> List<T> getSubscribersToClass​(Class<T> eventClass)
        See Also:
        EventService.getSubscribersToClass(Class)
      • getSubscribersToExactClass

        public <T> List<T> getSubscribersToExactClass​(Class<T> eventClass)
        See Also:
        EventService.getSubscribersToExactClass(Class)
      • getSubscribers

        public <T> List<T> getSubscribers​(Type eventType)
        See Also:
        EventService.getSubscribers(Type)
      • getSubscribers

        public <T> List<T> getSubscribers​(String topic)
        See Also:
        EventService.getSubscribers(String)
      • getSubscribersToTopic

        public <T> List<T> getSubscribersToTopic​(String topic)
        See Also:
        EventService.getSubscribersToTopic(String)
      • getSubscribers

        public <T> List<T> getSubscribers​(Pattern pattern)
        See Also:
        EventService.getSubscribers(Pattern)
      • getSubscribersByPattern

        public <T> List<T> getSubscribersByPattern​(String topic)
        See Also:
        EventService.getSubscribersByPattern(String)
      • getVetoSubscribers

        public <T> List<T> getVetoSubscribers​(Class<T> eventClass)
        See Also:
        EventService.getVetoSubscribers(Class)
      • getVetoSubscribersToClass

        public <T> List<T> getVetoSubscribersToClass​(Class<T> eventClass)
        See Also:
        EventService.getVetoSubscribersToClass(Class)
      • getVetoSubscribersToExactClass

        public <T> List<T> getVetoSubscribersToExactClass​(Class<T> eventClass)
        See Also:
        EventService.getVetoSubscribersToExactClass(Class)
      • getVetoEventListeners

        public <T> List<T> getVetoEventListeners​(String topicOrPattern)
        See Also:
        EventService.getVetoEventListeners(String)
      • getVetoSubscribersToTopic

        public <T> List<T> getVetoSubscribersToTopic​(String topic)
        See Also:
        EventService.getVetoSubscribersToTopic(String)
      • getVetoSubscribers

        public <T> List<T> getVetoSubscribers​(String topic)
        Deprecated.
        use getVetoSubscribersToTopic instead for direct replacement, or use getVetoEventListeners to get topic and pattern matchers. In EventBus 2.0 this name will replace getVetoEventListeners() and have it's union functionality
        Note: this is inconsistent with getSubscribers(String)
        See Also:
        EventService.getVetoSubscribersToTopic(String)
      • getVetoSubscribers

        public <T> List<T> getVetoSubscribers​(Pattern topicPattern)
        See Also:
        EventService.getVetoSubscribers(Pattern)
      • getVetoSubscribersByPattern

        public <T> List<T> getVetoSubscribersByPattern​(String pattern)
        See Also:
        EventService.getVetoSubscribersByPattern(String)
      • getSubscribersToPattern

        protected <T> List<T> getSubscribersToPattern​(Pattern topicPattern)
      • handleVeto

        protected void handleVeto​(org.scijava.event.bushe.VetoEventListener vl,
                                  Object event,
                                  org.scijava.event.bushe.VetoTopicEventListener vtl,
                                  String topic,
                                  Object eventObj)
        Handle vetos of an event or topic, by default logs finely.
        Parameters:
        vl - the veto listener for an event
        event - the event, can be null if topic is not
        vtl - the veto listener for a topic
        topic - can be null if event is not
        eventObj - the object published with the topic
      • setDefaultCacheSizePerClassOrTopic

        public void setDefaultCacheSizePerClassOrTopic​(int defaultCacheSizePerClassOrTopic)
        Sets the default cache size for each kind of event, default is 0 (no caching).

        If this value is set to a positive number, then when an event is published, the EventService caches the event or topic payload data for later retrieval. This allows subscribers to find out what has most recently happened before they subscribed. The cached event(s) are returned from #getLastEvent(Class), #getLastTopicData(String), #getCachedEvents(Class), or #getCachedTopicData(String)

        The default can be overridden on a by-event-class or by-topic basis.

        Parameters:
        defaultCacheSizePerClassOrTopic -
      • getDefaultCacheSizePerClassOrTopic

        public int getDefaultCacheSizePerClassOrTopic()
        Returns:
        the default number of event payloads kept per event class or topic
      • setCacheSizeForEventClass

        public void setCacheSizeForEventClass​(Class eventClass,
                                              int cacheSize)
        Set the number of events cached for a particular class of event. By default, no events are cached.

        This overrides any setting for the DefaultCacheSizePerClassOrTopic.

        Class hierarchy semantics are respected. That is, if there are three events, A, X and Y, and X and Y are both derived from A, then setting the cache size for A applies the cache size for all three. Setting the cache size for X applies to X and leaves the settings for A and Y in tact. Interfaces can be passed to this method, but they only take effect if the cache size of a class or it's superclasses has been set. Just like Class.getInterfaces(), if multiple cache sizes are set, the interface names declared earliest in the implements clause of the eventClass takes effect.

        The cache for an event is not adjusted until the next event of that class is published.

        Parameters:
        eventClass - the class of event
        cacheSize - the number of published events to cache for this event
      • getCacheSizeForEventClass

        public int getCacheSizeForEventClass​(Class eventClass)
        Returns the number of events cached for a particular class of event. By default, no events are cached.

        This result is computed for a particular class from the values passed to #setCacheSizeForEventClass(Class, int), and respects the class hierarchy.

        Parameters:
        eventClass - the class of event
        Returns:
        the maximum size of the event cache for the given event class
        See Also:
        setCacheSizeForEventClass(Class,int)
      • setCacheSizeForTopic

        public void setCacheSizeForTopic​(String topicName,
                                         int cacheSize)
        Set the number of published data objects cached for a particular event topic. By default, no caching is done.

        This overrides any setting for the DefaultCacheSizePerClassOrTopic.

        Settings for exact topic names take precedence over pattern matching.

        The cache for a topic is not adjusted until the next publication on that topic.

        Parameters:
        topicName - the topic name
        cacheSize - the number of published data Objects to cache for this topic
      • setCacheSizeForTopic

        public void setCacheSizeForTopic​(Pattern pattern,
                                         int cacheSize)
        Set the number of published data objects cached for topics matching a pattern. By default, caching is done.

        This overrides any setting for the DefaultCacheSizePerClassOrTopic.

        Settings for exact topic names take precedence over pattern matching. If a topic matches the cache settings for more than one pattern, the cache size chosen is an undetermined one from one of the matched pattern settings.

        The cache for a topic is not adjusted until the next publication on that topic.

        Parameters:
        pattern - the pattern matching topic names
        cacheSize - the number of data Objects to cache for this topic
      • getCacheSizeForTopic

        public int getCacheSizeForTopic​(String topic)
        Returns the number of cached data objects published on a particular topic. By default, no caching is performed.

        This result is computed for a particular topic from the values passed to #setCacheSizeForTopic(String, int) and #setCacheSizeForTopic(Pattern, int).

        Parameters:
        topic - the topic name
        Returns:
        the maximum size of the data Object cache for the given topic
        See Also:
        setCacheSizeForTopic(String,int), setCacheSizeForTopic(java.util.regex.Pattern,int)
      • getLastEvent

        public Object getLastEvent​(Class eventClass)
        Parameters:
        eventClass - an index into the cache, cannot be an interface
        Returns:
        the last event published for this event class, or null if caching is turned off (the default)
      • getCachedEvents

        public List getCachedEvents​(Class eventClass)
        Parameters:
        eventClass - an index into the cache, cannot be an interface
        Returns:
        the last events published for this event class, or null if caching is turned off (the default)
      • getLastTopicData

        public Object getLastTopicData​(String topic)
        Parameters:
        topic - an index into the cache
        Returns:
        the last data Object published on this topic, or null if caching is turned off (the default)
      • getCachedTopicData

        public List getCachedTopicData​(String topic)
        Parameters:
        topic - an index into the cache
        Returns:
        the last data Objects published on this topic, or null if caching is turned off (the default)
      • clearCache

        public void clearCache​(Class eventClassToClear)
        Clears the event cache for a specific event class or interface and it's any of it's subclasses or implementing classes.
        Parameters:
        eventClassToClear - the event class to clear the cache for
      • clearCache

        public void clearCache​(String topic)
        Clears the topic data cache for a specific topic name.
        Parameters:
        topic - the topic name to clear the cache for
      • clearCache

        public void clearCache​(Pattern pattern)
        Clears the topic data cache for all topics that match a particular pattern.
        Parameters:
        pattern - the pattern to match topic caches to
      • clearCache

        public void clearCache()
        Clear all event caches for all topics and event.
      • subscribeVetoException

        protected void subscribeVetoException​(Object event,
                                              String topic,
                                              Object eventObj,
                                              Throwable e,
                                              StackTraceElement[] callingStack,
                                              org.scijava.event.bushe.VetoEventListener vetoer)
        Called during veto exceptions, calls handleException
      • onEventException

        protected void onEventException​(String topic,
                                        Object eventObj,
                                        Throwable e,
                                        StackTraceElement[] callingStack,
                                        org.scijava.event.bushe.EventTopicSubscriber eventTopicSubscriber)
        Called during event handling exceptions, calls handleException
      • getRealSubscriberAndCleanStaleSubscriberIfNecessary

        protected Object getRealSubscriberAndCleanStaleSubscriberIfNecessary​(Iterator iterator,
                                                                             Object existingSubscriber)
        Unsubscribe a subscriber if it is a stale ProxySubscriber. Used during subscribe() and in the cleanup Timer. See the class javadoc.

        Not private since I don't claim I'm smart enough to anticipate all needs, but I am smart enough to doc the rules you must follow to override this method. Those rules may change (changes will be doc'ed), override at your own risk.

        Overriders MUST call iterator.remove() to unsubscribe the proxy if the subscriber is a ProxySubscriber and is stale and should be cleaned up. If the ProxySubscriber is unsubscribed, then implementers MUST also call proxyUnsubscribed() on the subscriber. Overriders MUST also remove the proxy from the weakProxySubscriber list by calling removeStaleProxyFromList. Method assumes caller is holding the listenerList lock (else how can you pass the iterator?).

        Parameters:
        iterator - current iterator
        existingSubscriber - the current value of the iterator
        Returns:
        the real value of the param, or the proxied subscriber of the param if the param is a a ProxySubscriber
      • removeProxySubscriber

        protected void removeProxySubscriber​(org.scijava.event.bushe.ProxySubscriber proxy,
                                             Iterator iter)
      • incWeakRefPlusProxySubscriberCount

        protected void incWeakRefPlusProxySubscriberCount()
        Increment the count of stale proxies and start a cleanup task if necessary
      • decWeakRefPlusProxySubscriberCount

        protected void decWeakRefPlusProxySubscriberCount()
        Decrement the count of stale proxies