Allow for configuring WebSocketClient JVM lifecycle

Signed-off-by: Lucas Fairchild-Madar <lfairchildmadar@flightstats.com>
This commit is contained in:
Lucas Fairchild-Madar 2017-08-25 11:23:08 -07:00
parent 2a3deb0a10
commit b680d1deea

View File

@ -77,6 +77,9 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
private final int id = ThreadLocalRandom.current().nextInt();
// defaults to true for backwards compatibility
private boolean stopAtShutdown = true;
/**
* Instantiate a WebSocketClient with defaults
*/
@ -378,21 +381,37 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
if (LOG.isDebugEnabled())
LOG.debug("connect websocket {} to {}",websocket,toUri);
init();
WebSocketUpgradeRequest wsReq = new WebSocketUpgradeRequest(this,httpClient,request);
wsReq.setUpgradeListener(upgradeListener);
return wsReq.sendAsync();
}
@Override
protected void doStart() throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("Starting {}",this);
if (isStopAtShutdown()) {
ShutdownThread.register(this);
}
super.doStart();
if (LOG.isDebugEnabled())
LOG.debug("Started {}",this);
}
@Override
protected void doStop() throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("Stopping {}",this);
ShutdownThread.deregister(this);
if (isStopAtShutdown()) {
ShutdownThread.deregister(this);
}
super.doStop();
@ -550,14 +569,6 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
return httpClient.getSslContextFactory();
}
private synchronized void init() throws IOException
{
if (!ShutdownThread.isRegistered(this))
{
ShutdownThread.register(this);
}
}
/**
* Factory method for new ConnectionManager
*
@ -694,6 +705,32 @@ public class WebSocketClient extends ContainerLifeCycle implements WebSocketCont
return this.httpClient;
}
/**
* Set JVM shutdown behavior.
* @param stop If true, this client instance will be explicitly stopped when the
* JVM is shutdown. Otherwise the application is responsible for maintaining the WebSocketClient lifecycle.
* @see Runtime#addShutdownHook(Thread)
* @see ShutdownThread
*/
public void setStopAtShutdown(boolean stop)
{
if (stop)
{
if (!stopAtShutdown && isStarted()) {
ShutdownThread.register(this);
}
}
else {
ShutdownThread.deregister(this);
}
stopAtShutdown = stop;
}
public boolean isStopAtShutdown() {
return stopAtShutdown;
}
@Override
public String toString()
{