Sending messages in an asynchronous manner avoid blocking the sending thread. This is a great where 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 and this can be configured using the
setSendTimeout
method in theRemoteEndpoint.Async
interface - secondly, the failure result manifests itself using the
Future
object orjava.websocket.SendResult
How do timeouts manifest ?
It depends on which strategy you’re using in order to send your messages
- Callback based
- Future (java.util.concurrent) 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()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
…. | |
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
…. | |
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
- eBook – Java WebSocket API Handbook
- Java WebSocket API specification
- Other WebSocket blogs
Cheers!