Java Web套接字服务器端点线程安全 [英] Java Web Socket ServerEndpoint Thread Safety
问题描述
单个ServerEndpoints线程是安全的还是属于在给定时间与之交互的所有客户端?
Are individual ServerEndpoints thread safe or do they belong to all clients who are interacting with them at a given time?
还是提出相同问题的另一种方式:
是ServerEndpoint类中的全局对象有造成并发问题的危险吗,
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?
此示例似乎表明每个端点都是线程安全的,或者他只是使用Set并祈祷并发问题
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?
因此,假设它们是线程安全的,容器(Tomcat,Glassfish等)是否分别创建ServerEndpoint类的新实例?
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?
推荐答案
B默认情况下,每个客户端连接都会创建新的 @ServerEndpoint
实例。 (这似乎也是最后一个问题的答案。)
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.
链接的示例使用 synchronizedSet
,因此似乎还可以。
Linked example uses synchronizedSet
, so it seems to be OK.
此外- @OnMessage
方法在之前的 @OnMessage
处理结束之前不会被触发,但是可以从其他线程调用它。这意味着您将始终按顺序处理传入消息。
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.
这篇关于Java Web套接字服务器端点线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!