Java Web Socket ServerEndpoint Thread Safety

左心房为你撑大大i 提交于 2019-12-07 07:22:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!