Skip to main content

WebSocket: Single Thread Model?

Posted by swchan2 on August 7, 2013 at 11:35 AM PDT

WebSocket is a bi-directional, full-duplex, TCP based messaging protocol. It is originally proposed as part of HTML5 and is a IETF-defined Protocol (RFC 6455). And W3C has defined JavaScript API for WebSocket which is in candidate recommendation since 2012-09-20.

JSR 356: Java API for WebSocket provides a standard Java API for creating WebSocket Applications. The specification provides an API for creating client and server endpoints. The reference implementation is integrated and available in GlassFish 4.0.

By default, a new instance of server endpoint is instantiated for each client connection (section 3.1.7 of JSR 356 specification). In other words, by default, WebSocket is "Single Thread Model". This is different from the default in Servlet (cf. javax.servlet.SingleThreadModel).
If we want to use a single instance of server endpoint for all client connections, then we can override the ServerEndpointConfig.Configurator#getEndpointInstance method. The following sample code illustrate how to achieve this.

First, we define a WebSocket endpoint with a custom configurator.

import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value="/secho", configurator=SEchoConfigurator.class)
public class SEchoServerEndpoint {

    @OnMessage
    public String echo(String message) {
        return message;
    }
}

Second, we define a ServerEndpointConfig.Configurator and override the getEndpointInstance method.

import javax.websocket.server.ServerEndpointConfig;

public class SEchoConfigurator extends ServerEndpointConfig.Configurator {
    private static SEchoServerEndpoint theSEchoServerEndpoint = new SEchoServerEndpoint();

    @Override
    public T getEndpointInstance(Class endpointClass) throws InstantiationException {
        if (SEchoServerEndpoint.class.equals(endpointClass)) {
            return (T)theSEchoServerEndpoint;
        } else {
            throw new InstantiationException();
        }
    }
}