Class BackgroundEventSource

  • All Implemented Interfaces:
    java.io.Closeable, java.lang.AutoCloseable

    public class BackgroundEventSource
    extends java.lang.Object
    implements java.io.Closeable
    A wrapper for EventSource that reads the stream on a worker thread, pushing events to a handler that the caller provides.

    A BackgroundEventSource instance manages two worker threads: one to start the stream and request events from it, and another to call handler methods. These are decoupled so that if a handler method is slow to return, it does not completely block reading of the stream.

    This is the same asynchronous model that was used by EventSource prior to the 4.0.0 release. Code that was written against earlier versions of EventSource can be adapted to use BackgroundEventSource as follows:

    
         // before (version 3.x)
         EventHandler myHandler = new EventHandler() {
           public void onMessage(String event, MessageEvent messageEvent) {
             // ...
           }
         };
         EventSource es = new EventSource.Builder(uri, myHandler)
           .connectTimeout(5, TimeUnit.SECONDS)
           .threadPriority(Thread.MAX_PRIORITY)
           .build();
         es.start();
         
         // after (version 4.x)
         BackgroundEventHandler myHandler = new BackgroundEventHandler() {
           public void onMessage(String event, MessageEvent messageEvent) {
             // ... these methods are the same as for EventHandler before
           }
         };
         BackgroundEventSource bes = new BackgroundEventSource.Builder(myHandler,
             new EventSource.Builder(
               ConnectStrategy.http()
                 .connectTimeout(5, TimeUnit.SECONDS)
                 // connectTimeout and other HTTP options are now set through
                 // HttpConnectStrategy
               )
           )
           .threadPriority(Thread.MAX_PRIORITY)
             // threadPriority, and other options related to worker threads,
             // are now properties of BackgroundEventSource
           .build();
         bes.start();
     
    Since:
    4.0.0
    • Method Detail

      • start

        public void start()
        Starts the worker thread to consume the stream and dispatch events. This also starts the underlying EventSource if it has not already been started.

        This method has no effect if the BackgroundEventSource has already been started, or if close() has been called.

      • getEventSource

        public EventSource getEventSource()
        Returns the underlying EventSource.
        Returns:
        the EventSource
      • close

        public void close()
        Shuts down the BackgroundEventSource and the underlying EventSource.

        The BackgroundEventSource cannot be started again after doing this.

        Specified by:
        close in interface java.lang.AutoCloseable
        Specified by:
        close in interface java.io.Closeable