Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Jetty websocket client class WebSocketClient thread safe?

Jetty 9.3

Java 8

Is org.eclipse.jetty.websocket.client.WebSocketClient thread safe.

Can multiple threads use a single instance of this class to create a websocket session (with the connect method) ?

like image 863
benbenw Avatar asked Nov 30 '16 21:11

benbenw


2 Answers

It's not, from the code here is at least one example why:

The purpose of WebSocketClient is to provide a mean of establishing connections to remote websocket endpoints.

This is achieved by calling connect() method, which returns Future Session. All right, now imagine that

  1. Thread 1 instantiates a WebSocketClient and calls setCookieStore()

  2. Thread 1 calls connect(Object websocket, URI toUri).

  3. Inside connect() Thread 1 executes

    ClientUpgradeRequest request = new ClientUpgradeRequest(toUri)
    

    and

    request.setRequestURI(toUri)
    
  4. Thread 2 executes setCookieStore(CookieStore cookieStore)

Then the request created by Thread 1 may have the cookies corresponding to the URI of Thread 2.

In order to ensure thread safety the internal state of the object should de unmodifiable during the whole connection process.

like image 155
Serg M Ten Avatar answered Oct 11 '22 21:10

Serg M Ten


I can't guarantee that WebSocketClient is 100% thread safe, but I can say that it is meant to be thread safe, to a certain extent.

Looking at the source code, we see that the private method initializeClient is synchronized:

private synchronized void initializeClient() throws IOException 

and that the connect method is using an Executor:

// Execute the connection on the executor thread
executor.execute(promise);

The documentation of the class says nothing about thread safety, but the call of the synchronized initializeClient method from the connect method and the use of the Executor are clear signs that some form of multi-threading is supported.

== Edit ==

Thread safety is often guaranteed only for certain types of operations. For examples it can be guaranteed only for read operations and not for write operations. This is the role of the documentation to define the conditions of thread safety. The remark of Sergio Montoro is right, if one thread modify the object during its use by another thread, strange things could happens. In the case of WebSocketClient thread safety is certainly at least restricted to the non-modification of the object by other threads, or to the synchronized and concerted modification of the WebSocketClient internal state.

like image 42
Ortomala Lokni Avatar answered Oct 11 '22 21:10

Ortomala Lokni