Class BackgroundEventSource
java.lang.Object
com.launchdarkly.eventsource.background.BackgroundEventSource
- All Implemented Interfaces:
Closeable,AutoCloseable
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
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringDefault value forBackgroundEventSource.Builder.threadBaseName(String). -
Method Summary
-
Field Details
-
DEFAULT_THREAD_BASE_NAME
Default value forBackgroundEventSource.Builder.threadBaseName(String).- See Also:
-
-
Method Details
-
start
public void start()Starts the worker thread to consume the stream and dispatch events. This also starts the underlyingEventSourceif 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
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:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-