Accessing servlet scoped beans from another thread

吃可爱长大的小学妹 提交于 2019-12-25 07:19:01

问题


I am using approach from the "Accessing scoped proxy beans within Threads of" answer. However I am seeing rare deadlocks involving RequestAttributes object. The main reason of the deadlock is between the synchronized (this.sessionAttributesToUpdate) statement in the object and servlet session hash-map. Normally the instances of the object are created for each request, so they don't clash, but if I pass the object to another thread to use the session beans, the same object is used and it causes deadlock sometimes.

The deadlock happens if current http request is not completed while the another thread starts using a session bean passed with RequestContextHolder.setRequestAttributes.

I think this guy mentions the same problem, but his question is unanswered: Session scoped bean encountering deadlock.

So, any ideas how to avoid the deadlock?


回答1:


Here's an answer that provides alternative solution considering the objective is to calculate something in background while user is navigating pages.

Possibility 1: Create a service bean with processing method that is annotated with @Async (http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html) that returns a result of computation in a Future object. Store the Future object in the session. Access the result in subsequent requests through Future object if task is completed. Cancel the the task via Future.cancel if session is to be destroyed before task is completed.

Possibility 2: Take a look if new features of Spring 3.2 and Servlet 3.0 async processing can help you: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-async

Possibility 3: Emulate a task queue. Create a singleton service that can put objects to structure like ConcurrentMap where key would be some job id (you can than store key into session) and value the result of background processing. Background thread would then store objects there (this is perhaps not much better than accessing session directly, but you can make sure it's thread safe).



来源:https://stackoverflow.com/questions/15768556/accessing-servlet-scoped-beans-from-another-thread

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