1

I have a method doSomething(int param) in a JSF View Scoped Bean, that has to be used only by one thread and when this method is called from another thread (another user), it has to show a user message while it is still in use by the first thread (first user).

I know that I have to use "synchronized" but how to achieve this? and how to show the message to the user calling it while it is in use?

Thanks in advance for the help.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

0

In my opinion what you are trying defend from is impossible anyway.

According to the JSF specification @ViewScoped annotated beans live only in the context of one user (session) and only for the time a particular view is in use. When another user (or even the same user from a different browser / tab) enters the same view, a new instance of the bean would be created.

View (@ViewScoped): View scope persists during a user’s interaction with a single page (view) of a web application.

The only time there can be a problem with @ViewScoped thread safety is when the application does not implement any client side ajax request queuing and that is the only situation where you should consider placing some synchronized blocks in your bean.

If this is not the case then only @SessionScoped and @ApplicationScoped beans should be considered for thread safety.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
  • Thanks for the replies. After some search and based on your answer and that of BalusC, I hope my following understanding is right: In case of View Scoped Beans (namely Request Scoped Beans) the keyword "synchronized' does not have any effect since there will be a new instance of view bean that will be created each time a new session (maybe a new user) accesses the same view. – jocopernicus Jan 26 '17 at 07:37
  • In fact due to time constraint I cannot refactor the already existing code of the application to manage scopes in a better way (I mean considering Session or Application Scope for thread safety). So as a solution to prevent the use of the same method by more than one user at the same time: I am thinking to use a static flag of type boolean, and in the beginning of the method I check via this flag whether the concerned method is in use or not, if not then the flag is set to true and after finishing the method it should be set again to false. Maybe not a clean solution. what do you think please? – jocopernicus Jan 26 '17 at 07:38
  • No, dont synchronize your code in this way. Use the standard synchorized indentifier or if you want to be more elaborate go for the features of the java.util.concurrent package. If someone would be setting flags for concurrency in amy application he would get passed my review for sure. – Maciej Kowalski Jan 26 '17 at 11:35