This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Do static objects exist for the lifetime of an application? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Do static objects exist for the lifetime of an application?" Watch "Do static objects exist for the lifetime of an application?" New topic

Do static objects exist for the lifetime of an application?

Yan Lee
Ranch Hand

Joined: Sep 15, 2003
Posts: 94
I want to have a HashMap that holds a few key value pairs for the application.
The HashMap should be availible as long as the application is alive.
I should be able to add/remove objects from the HashMap.

Can I achieve the above requirements if I make the HashMap instance static
and do initialization in a static initializer block?

Thanks in advance for the help.
Cameron McEwan

Joined: Feb 25, 2005
Posts: 4
In short yes as long as you are instanciating only one JVM. However do you really need to do this, this is not always the best design choice? If the answer is yes then check out the Singleton Pattern note however this is one of the most overused and misunderstood patterns of them all here is a link
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Yes, that would work. However, I would like to point out that there are other options depending on other things. Here are a few things you might want to consider: What is the purpose of this HashMap? When does this it need to be created (i.e. what is the earliest method in the program that needs to access it)? What class should be in charge of creating it (whether it's a static or non-static member)? What other classes need access to the HashMap?

There may be other considerations to think about, too, but these are the ones that come to mind. Depending on your answers to these questions, one option is to create it in main() or the constructor of one of your major classes then pass it as a parameter to other constructors or methods. I'm sure there are other alternatives, but everything I can think of are basically variations on this theme.

Anyway, I hope this gives you some ideas to think about. Personally, I don't like to lock myself into one particular option without considering other alternatives. And when it comes to design, there are almost always other alternatives.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Do static objects exist for the lifetime of an application?
It's not a secret anymore!