Java Bean Thread Safety

I've been using JavaBeans for years now, and have read at least 30 different texts and online resources about using Java beans in JSPs. But in every single one of them, they are ambiguous and non-committal about how to properly use them to avoid Thread-Safety problems in a multithreaded (web server) environment. Are there any true Java gurus out there who know how to do so in JSPs?

Specifically, when you use the <jsp:useBean> tag, that tag automatically binds an instance of your bean to the PageContext object. Since the PageContext object is shared by many threads, wouldn't this automatically make all of the Java Bean's properties vulnerable for thread problems? Since the pageContext is shared between threads, wouldnt one have to declare every one of the bean's setters and getters as "synchronized", to prevent one thread overwriting another's values?

I ask because in many texts, they make a vague suggestion "be sure to write your beans thread-safe"--but provide no concrete answer as to how (the level at which to declare 'synchronized'). But in all their code examples, I have never once, in all these years, seen the word "synchronized".

How is this possible? Wouldn't the bean, as bound to the thread-shared pageContext object, be completely exposed to thread corruption, with multiple threads simultaneously calling its methods?

Can someone supply some code snippets showing the thread-safe way to use JavaBeans (i.e., where to synchronize)

[1505 byte] By [agentorange07a] at [2007-11-27 8:04:40]
# 1

PageContext is shared by many threads?

Not at one time, I'm pretty certain of that.

From the API: A PageContext instance is obtained by a JSP implementation class by calling the JspFactory.getPageContext() method, and is released by calling JspFactory.releasePageContext().

The to me suggests the contract that a PageContext can only be in use by on one JSP page at a time. As far as I am concerned, pageContext can be treated like a "local variable" to a jsp page.

The contents of the pageContext object are maybe a different story, but we'll get to that.

The things to worry about with thread safety are the same as they are for servlets.

1 - Class attributes are not threadsafe. ie variables declared within <%! %> signs

2 - Session attributes are potentially not threadsafe if the user makes two quick requests in a row (handling two requests for the same session)

3 - Application attributes are never threadsafe as any currently running request can access them. Most Application level attributes I treat as read only (kinda like Singleton access)

I don't see the need to go overboard declaring everything "synchronized". In fact I think it would be hugely detrimental.

evnafetsa at 2007-7-12 19:47:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...