File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes static objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "static objects" Watch "static objects" New topic

static objects

Suresh Appagundi
Ranch Hand

Joined: Sep 22, 2003
Posts: 44
I have the following program with static block inside
public class Test {

private static HashMap hMap;
static {
hMap = new HashMap();
hMap.put(new Integer(1),"DDD")
hMap.put(new Integer(2),"HHH")
hMap.put(new Integer(3),"JJJ")

public Test(){}
public static String getValue(int iKey) {
// which will return the value for the key passed in,
// fetching it from HashMap.
// Imports are not shown

Iam using above program in my web application. I want hMap object to be there for ever until i restart my web server.
Now if the hMap is not used for long time and if garbage collector releases this hMap (remember hMap is a static object) to allocate memory for some other object, my getValue method will give error.
Or is it that there will be seperate memory storage area for static objects or variables(static storage memory other than heap), which will hold only static objects or variables until the application is running.
Thanks in advance
Rajan Punchouty

Joined: Mar 15, 2004
Posts: 21
As you said u r using it in your web application... u can definitly put ur object in application context scope....and access it from any servlet or jsp and will be available thru out.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Jesus Christ,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Moving this to the Servlets forum, as that's about the closest forum we have for general web application questions.
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33117

Static variables don't get garbage collected. This can lead to memory leak type situations if hMap gets too big. You don't have to worry about errors though because the static variables will keep their values until you restart the app.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
I agree. Here's the link:
subject: static objects
It's not a secret anymore!