Multithreading Considerations
As you have seen, putting business logic in beans leads to a more structured and maintainable application. However, there’s one thing you need to be aware of: beans shared between multiple pages must be thread safe.
Thread safety is an issue for beans only in the session and application scopes. Beans in the page and request scope are executed by only one thread at a time. A bean in the session scope can be executed by more than one thread initiated by requests from the same client. This may happen if the user brings up multiple browsers, repeatedly clicks a submit button in a form, or if the application uses frames to request multiple JSP pages at the same time. All application users share application scope beans, so it’s very likely that more than one thread is using an application scope bean.
Java provides mechanisms for dealing with concurrent access to resources, such as synchronized blocks and thread notification methods. But there are other ways to avoid multithreading issues in the type of beans used in JSP pages.
Value beans are typically placed in the request or session scope as
containers for information used in multiple pages. In most cases,
they are created and initialized in one place only, such as by a
Controller servlet or by a <jsp:useBean>
and
<jsp:setProperty>
combination in the request processing page invoked by a form, or by a custom action or utility bean. In all other places, the bean is used only within EL expressions or by the ...
Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.