Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Web Socket ServerEndpoint Thread Safety

Are individual ServerEndpoints thread safe or do they belong to all clients who are interacting with them at a given time?

Or another way to ask the same question: Are global objects in the ServerEndpoint class in danger of creating concurrency issues, like they do in HttpServlets?

This example seems to indicate that each Endpoint is thread-safe, or he is just using Set and praying that concurrency issues don't pop up?

So, assuming that the they are thread safe, does the container (Tomcat, Glassfish, etc.) create new instances of the ServerEndpoint class each time a new connection from a distinct client is established?

like image 369
adv Avatar asked Oct 18 '22 13:10

adv


1 Answers

By default, each client connection creates new @ServerEndpoint instance. (this seems to be the answer for the last question as well).

Static objects (or access to them) MUST be synchronized.

Linked example uses synchronizedSet, so it seems to be OK.

Additionally - @OnMessage method won't be triggered before previous @OnMessage processing ends, BUT it can be invoked from different thread. Meaning you will always process incoming messages sequentially.

like image 138
Pavel Bucek Avatar answered Oct 21 '22 16:10

Pavel Bucek