问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/36048288/java-web-socket-serverendpoint-thread-safety