aspose file tools*
The moose likes Servlets and the fly likes Any difference between Context and Static variables ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Any difference between Context and Static variables ?" Watch "Any difference between Context and Static variables ?" New topic
Author

Any difference between Context and Static variables ?

Matteo Di Furia
Ranch Hand

Joined: Jun 20, 2008
Posts: 102
Ehy ranchers,
I'm here again to ask your opinion on a little problem I'm facing right now.
So, I got some data which will not change over the total life of my web application, hence I want to cache it somewhere. I'm not in the need to use some tool like EhCache, since data will be retrieved only once when the application starts and stored until the application is stopped.
Now I'm thinking where to put these informations, and I'm basically thinking at two places :

1) as a Context attribute.
2) as a static variable of a class, specifically built to load and store these static data.

If I had to think about these two solutions, I can't find any significant difference between them, excepting how you access them (if I use the context, I'll need a reference to it somehow, while if I use a static variable I can access it directly calling my class).
So, I'm looking for suggestions from more experienced people about this issue. Also, feel free to suggest any other solution you happened to discover as effective for this kind of problems.
Thank you very much.

Matteo Di Furia
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 29274
    
140

Matteo,
I'd go with the static variable so it can be accessed from anywhere in your application. Either way is correct of course.

The only advice I can think of is to watch the size of the static data. If it is huge, you may want to use "WeakReferences" or look at loading it on demand so only pieces get used. If it is small (or medium sized), loading up front works fine.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60071
    
  65

For things that are specific to the presentation layer, I'll prefer the application context over static variables. It not only just feels architecturally cleaner, it makes them available to JSP pages via the EL.
[ October 22, 2008: Message edited by: Bear Bibeault ]

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Originally posted by Matteo Di Furia:

Now I'm thinking where to put these informations, and I'm basically thinking at two places :

1) as a Context attribute.
2) as a static variable of a class, specifically built to load and store these static data.



HI,

context-param(define in web.xml) or Context attribute ?
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2713
    
    5

Originally posted by seetharaman venkatasamy:

context-param(define in web.xml) or Context attribute ?


Why? what is the difference?


SCJP, SCWCD.
|Asking Good Questions|
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Originally posted by Amit Ghorpade:
Why? what is the difference?


If I am not mistaken, when we say context-param, we usually refers to init parameters, what we defined in web.xml. While attributes, the object we bind with the application context, session, request, on runtime, we bind as attribute.
Matteo Di Furia
Ranch Hand

Joined: Jun 20, 2008
Posts: 102
Well, I think I'll throw in some more input to let this discussion go into the right direction.
First of all, I mean context attributes, not params, I will not set them in web.xml, some listener will fetch and store the data as a context attribute.
On second instance, data will be related to both presentation and business.
Just to give you an idea, imagine a system managing users and groups. The number of groups if fixed (or can grow really low), so I thought about storing a map of those groups in my cache (allow me to use this term, it's a cache after all) and to not execute a query every time I need them. I'll have something like 5/10 maps of data like this simple examples, of course each one holding different kinds of data.
Another thing I'd like to store is the localization bundle. This is readonly, so I'll store only one instance for each language supported by the web app, each instance shared by the users that visualize that language.

I know that I have to throw an eye to memory usage, but this way I'll have all static data quickly available and accessible via a single class, which will also provide me with more maintainability and ease of use. Also, I doubt I'll use too much memory, it's not that big data after all.
[ October 23, 2008: Message edited by: Matteo Di Furia ]
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Assuming your localization bundle can be a ResourceBundle. And only one instance means can be a Singleton. Why are you storing this to application context? We can make this without storing to any context. Just inject it where its needed. Am I getting the thing right?
Matteo Di Furia
Ranch Hand

Joined: Jun 20, 2008
Posts: 102
I got localization bundles on files. I need to load data from files, and I'd like to load it only once.
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Originally posted by Matteo Di Furia:
I got localization bundles on files. I need to load data from files, and I'd like to load it only once.


Most probably properties file. Thats what I mean when said, ResourceBundle. However, you need not bind these to any of your contexts. Just inject (provide the sole reference of) it where you are using it. For example any Controller needs to use it, or any Validator....
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Originally posted by Matteo Di Furia:
Well, I think I'll throw in some more input to let this discussion go into the right direction.
First of all, I mean context attributes, not params, I will not set them in web.xml, some listener will fetch and store the data as a context attribute.


Then it is not good idea to store the value in context attribute..

because it is not a thread safe. when you say context-param(in web.xml)...it is read only .. so it is thread safe

although remember there is only one context per application.

Hope This Helps
Matteo Di Furia
Ranch Hand

Joined: Jun 20, 2008
Posts: 102
@ Seetharaman :
I understand what you say, but the fetching and storing of the data will be done by a class called in an ApplicationListener, i.e. when the application starts, hence before any request is elaborated. I think I should not worry about thread safety, since I only have one ApplicationListener (under these conditions, only one thread will write data, before any other thread could try to read it).

@ Adeel :
I admit I must improve my knowledge about ResourceBundle, more specifically I have to discover how the loading of bundle properties from file works. If the loading just happens once, then I'm fine and I can inject it directly. Instead, if the creation of the ResourceBundle means that the properties are loaded from files every time, then I think there's room for improvement.
(I feel this problem is out of topic, I'll open another one on this argument if I can't find some answers on the web).

Back on topic : so, it seems there's no much difference between the two solutions. I'll apply the one that's easier to use for me then. Thank you all for partecipating and sharing your knowledge.
[ October 23, 2008: Message edited by: Matteo Di Furia ]
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Thanks Matteo Di Furia ....Carry on
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Originally posted by Matteo Di Furia:
I understand what you say, but the fetching and storing of the data will be done by a class called in an ApplicationListener, i.e. when the application starts, hence before any request is elaborated. I think I should not worry about thread safety, since I only have one ApplicationListener (under these conditions, only one thread will write data, before any other thread could try to read it).


There can be a thread-safety issue, unless you have done it carefully, using synchronized access. Because our Servlet API make use of multi-threading behind the scene. As you said, "only one thread will write data, before any other thread could try to read it". You probably wouldn't get any issue then.


I admit I must improve my knowledge about ResourceBundle, more specifically I have to discover how the loading of bundle properties from file works. If the loading just happens once, then I'm fine and I can inject it directly. Instead, if the creation of the ResourceBundle means that the properties are loaded from files every time, then I think there's room for improvement.
(I feel this problem is out of topic, I'll open another one on this argument if I can't find some answers on the web).


No that would be absurd. Usually, our controllers, validators, DAOs, all used to be Singleton, since they don't have any state related thing in there. So, you will just instantiate your resource bundle once, and use everywhere its needed. A way can be to employ Factory Pattern to get the appropriate resource bundle.
[ October 23, 2008: Message edited by: Adeel Ansari ]
Matteo Di Furia
Ranch Hand

Joined: Jun 20, 2008
Posts: 102
Adeel,
so you say I instantiate my resource bundle once. But then, if it is not a singleton, where should I store my instance of bundle ? Make it as a singleton or store it in my cache. I know the difference is slight, probably to make a singleton would be cleaner, but consider that I want to centralize the control of static data to later add functionality (for system administrators only) to reload this data on demand (I'll make sure to resolve any clash about thread safety, yes), for example if some new keys are added to resource bundles, I'd like to let the admin to load them dinamically without the need to restart the entire web application. Sure, I could also add this functionality to the class holding the reference of the resource bundle singleton, but I'd prefer to centralize the mechanics of cached object functions in a unique place (I yet designed a class diagram to perform data loading, storing and refreshing independently from data sources, I just need to know where would be the best option to save this data in).
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Have a look into Factory Pattern. You will intialize your factory in the start and then ask for a desired resource bundle. It will load the bundle - for the first time - and provide you the bundle. Simple is that. The bundle reference will reside in the Factory itself. This way you can achieve a centralized place.

Moreover, you might want to look into Apache Commons Configuration regarding reloading the resource bundle on a defined criteria.
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Here is the link. Principles, Patterns, and Practices: The Factory Pattern
Matteo Di Furia
Ranch Hand

Joined: Jun 20, 2008
Posts: 102
Adeel,
yes, Factory Pattern is what I'm coding, with the sole difference that data is not stored in the factory itself, but in a centralized place, and that a centralized system will call the factory to load/reload data on demand. This way, to handle multiple sets of cached data, I will not call multiple factories, just my centralized class which will know which factory to call.
(Thinking about it, I'm coding something that I'd get with EhCache, but whatever. I think I might be better to stick with EhCache and Common Configuration :-/ )
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Looks fine and you know what you are doing. All the best.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Any difference between Context and Static variables ?
 
Similar Threads
What is Static Variable?...
Dealing with multi-threading in servlets
Large Java Class
Prepared Stmt or Stored Procedure ?
Jersey client architecture question.