Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Use Asynchronous Timeouts in the Java Websocket API

DZone's Guide to

How to Use Asynchronous Timeouts in the Java Websocket API

In this post we take a look at how to deal with timeouts when using the Java WebSocket API. Read on to find out how and for some example code.

· Integration Zone
Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

Sending messages in an asynchronous manner avoids blocking the sending thread. This is great when your solution needs to scale in order to support a large number of clients, but there is a limit on how long can we wait for the asynchronous process to complete.

The Java WebSocket API gives you a few options in this regard.

Async Timeout Support

  • First and foremost, there is a notion of a timeout. This can be configured using the setSendTimeout method in the RemoteEndpoint.Async interface.
  • Secondly, the failure result manifests itself using the Future object or java.websocket.SendResult.

How Do Timeouts Manifest?

It depends on which strategy you’re using in order to send your messages:

  • Callback-based.
  • Future-based.

In case you are using the java.websocket.SendHandler, i.e. the callback handler route, the timeout exception details will be available via SendResult.getException()

....
public void broadcast(Session s, String msg){
  RemoteEndpoint asyncHandle = s.getRemoteAsync();
  asyncHandle.setSendTimeout(1000); //1 second
  asyncHandle.sendText(msg, 
    new SendHandler(){
      @Override
        public void onResult(SendResult result) {
        if(!result.isOK()){
        System.out.println("Async send failure: "+ result.getException());
        }
    }
  }); //will timeout after 2 seconds
  tracker.get(); //will throw java.util.ExecutionException if the process had timed out
}
....

If you chose to use the Future to track the completion, calling it get method will result in a java.util.concurrent.ExecutionException.

....
public void broadcast(Session s, String msg){
  RemoteEndpoint asyncHandle = s.getRemoteAsync();
  asyncHandle.setSendTimeout(2000); //2000 ms
  Future<Void> tracker = asyncHandle.sendText(msg); //will timeout after 2 seconds
  tracker.get(); //will throw java.util.ExecutionException if the process had timed out
}
....

Further Reading

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
websocket ,api ,integration ,timeouts

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}