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) ?
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) ?
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.
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
Thread 1 instantiates a WebSocketClient
and calls setCookieStore()
Thread 1 calls connect(Object websocket, URI toUri)
.
Inside connect()
Thread 1 executes
ClientUpgradeRequest request = new ClientUpgradeRequest(toUri)
and
request.setRequestURI(toUri)
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.
volatile
. Otherwise a thread could change the value and the other don't see the change. Also I don't see in the class how to keep two sets of cookies: the shared among threads subset and the per-thread subset. Moreover, is it possible to think of a reasonable use case for splitting cookies this way in two subsets? –
Ciracirca © 2022 - 2024 — McMap. All rights reserved.