I know this is a fundamental question on Java’s static variables, but I would like an official answer, maybe a pointer to the right documentation.
I am using a static variable to cache the results from the database. Question is, will these results be shared among all users of the web application?
Here’s my code:
private static TreeMap<String,String> cachedOwners = null;
public static TreeMap<String,String> fetchOwners( )
throws Exception
{
if ( Owners.cachedOwners != null )
{
return Owners.cachedOwners;
}
DBHandler db = DBHandler.getInstance( );
Owners.cachedOwners = db.fetchCAROwners( );
return Owners.cachedOwners;
}
Now, based on my tests, caching works and the static variable “cachedOwners” is shared among all users of the application.
How come this happens? I thought a static variable is only tied to a user’s session.
Yes!
There is not only one official documentation because there are two sides together
Static means the same address in the classloader-inheritation, so, if you ever have two webapplications using the same inherted “classloader”.
i.e. if you have an singeton.jar with an
an the singleton.jar is located in
only the “tomcat/lib” will be define the born-field because the /lib-classloader will be load first.