线程安全控制器和实用程序类?
所以我使用 Spring MVC 并在我的控制器中调用几个实用程序类。我在这些实用程序类中使用的集合是否需要同步?同样,当每个用户访问控制器中的网页时,是否会为每个用户生成多个线程,这意味着我需要确保线程安全?
So I'm using Spring MVC and in my controller I call several Utility classes. Do the Collections I use in those utility classes need to be synchronized? Similarly, are multiple threads spawned for each user when they access my webpage in the controller meaning I need to ensure thread-safety?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每个请求都将由 servlet 容器(来自线程池)分配的某个任意线程处理,因此多个请求将意味着控制器的多个并发执行。用户和线程之间没有直接关联,只有请求和线程,但如果您有多个用户,那么通常会有并发请求,因此有多个线程。
鉴于控制器应该是线程安全的,您将需要确保控制器使用的实用程序类和集合是线程安全的,无论是通过设计(例如,使它们或控制器请求或可能的会话范围,如果您确保同一会话不能并发服务)或通过使用共享资源上的锁定。
Each request will be handled by some arbitrary thread allocated by the servlet container (from a thread pool), so multiple requests will mean multiple concurrent executions of the controller. There is no direct correlation between users and threads, just requests and threads, but if you have multiple users, then you typically have concurrent requests, and so multiple threads.
Given that controllers should be thread-safe, you will then need to ensure your utility classes and collections used by the controller thread-safe, either by design (e.g. making them or the controller request or possibly session scope if you ensure the same session cannot be served concurrently) or by use of locking on shared resources.
一般来说,你应该很好,但这里有一篇非常好的文章,讨论了 Spring Web 应用程序中的线程安全,Spring MVC 中的线程安全控制器。
Generally you should be good, but here is a very good article that talks about thread safety in spring web applications, Thread safe controllers in Spring MVC.