If you make the bean class have a private constructor and a static reference
to an instance of its own class, then there will always be a strong
reference from the class itself to the instance of the class.  (The first
call to bean.getInstance() instantiates the private static member variable
which is your singleton instance of your bean, the contructor does the db
work etc.)

Therefore, it won't get gc'd.

That's the way I do my classes that do that kind of stuff, anyway.

-----Original Message-----
From: Jeff Kilbride [mailto:[EMAIL PROTECTED]]
Sent: Friday, 18 May 2001 9:35 AM
To: [EMAIL PROTECTED]
Subject: Bean Choices (code question)


I'm sorry if this is a little off-topic, since it is more about java code,
but I thought Tomcat users would be interested/knowledgeable about the way
beans work.

I have a lot of informational beans that hold static reference data (think
ISO codes, State abbreviations, etc...) With these types of beans, I have
the choice of instantiating a singleton object reference to the bean and
accessing the methods through the object, or making all the methods "public
static" so I can access them via BeanName.method(). For the former, the bean
does all of it's initialization and database access in it's constructor and
my JSP's have something like the following at the top:

<%!
    private static BeanName bean = BeanName.getInstance();
%>

For the latter, the bean does all of it's initialization and database access
in a static block:

static {
    // bean initialization and DB access
}

and my JSPs reference the static methods:

<%= BeanName.method() %>

My question concerns the way beans with all "public static" methods are
instantiated and garbage collected. Because these beans hold unchanging
reference info, I only want the data loaded from the database once the first
time the bean is referenced. For beans with all "public static" methods,
since there are no object references to them, when are they garbage
collected? Is it possible that the bean will be unloaded and the code in my
static block will be re-run when the bean is next referenced? Or do these
all static objects somehow stick around forever? For the singleton, I know
the object will last as long as the JSP is loaded, because there is a
definite object reference to the singleton. I'm a little unclear as to what
happens with a bean that has all "public static" methods, though.

Can anyone shed some light on this?

Thanks,
--jeff


Reply via email to