OK I know this isn't Tomcat-specific, but my post on Sun Forums didn't get
much of a reply, so I thought I'd try it here.


I'm in the process of translating a series of JSPs into straightout servlets
and I have a question about how I should replicate the functionality of the
useBean directive in my Servlet.

I have a set of Beans that mediate between the JSP and a database (actually
btwn JSP and a class that accesses the db). These beans cache results from
the database, cutting back on back and forth traffic. They timeout after
varying periods of time, flush their memory (hashmaps) and then reload as
needed.

I've used the useBean directive with no problem, it's just that now the
project has grown in complexity to where it needs to be re-written as a set
Servlets.

My solution for replacing the useBean functionality has been a BeanBag class
with the following form:

class BeanBag {
private static AppleBean appleBean = null;
private static BananaBean bananaBean = null;

public static AppleBean getAppleBean() {
if (appleBean == null) {
appleBean = new AppleBean();
}
return appleBean;
}

..... and so on
}

In the Servlet code, I just obtain a bean like this:
AppleBean appleBean = BeanBag.getAppleBean();

My question is: where (or if) should I implement the synchronization?

The generated servlets that Tomcat creates for the useBean directive uses
Synchronized Statements, like this:
synchronized (application) {
appleBean = (com.fruitsalad.AppleBean)
_jspx_page_context.getAttribute("appleBean", PageContext.APPLICATION_SCOPE);
if (appleBean == null){
appleBean = new com.fruitsalad.AppleBean();
_jspx_page_context.setAttribute("appleBean", appleBean,
PageContext.APPLICATION_SCOPE);
}
}

But wouldn't making the methods in BeanBag synchronized be a better
approach?

Thanks

Reply via email to