Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton or Context parameter  RSS feed

 
Petr Blahos
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

What do you think, is it better to have an object
that should be common to all my servlets defined
as a context attribute, i.e. initialize it in a
ContextListener, like:

or is it better to have a singleton object? You see,
handling of a singleton seems to be easier to me. I am
just thinking if there isn't any hitch in having a static
member. Like, what if I have the application deployed 2x
on 2 different paths in one servlet container? Will it
work?

Thanks,
Petr
 
Colin Fletcher
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on what you are doing. If you are doing lightweight stuff, singleton works, might not be the best practice... If you are doing heavy stuff, context.

If you have a distributed application (> 1 VM) there will be an instance of the context object in each VM.

I wrote a database connection pooling object tied it to the contextInitialized and destroyed routines and wola. If I decide to distribute my application the object will exist in each vm.

Hope it helps.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65826
134
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I avoid singletons like the plague for these kind of purposes. There is too much possibility of unintended interactions. What if, for example, more than one web app are sharing the same JVM?
 
Sheldon Fernandes
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bear Bibeault:
What if, for example, more than one web app are sharing the same JVM?

Would this be a problem if the classes are in WEB-INF/lib or WEB-INF/classes of each web app? They may be duplicated in all web apps which require them. Would there be any unintended interactions in this case? (Assuming Servlet 2.3)

If the above answer is no, then what other factors/considerations would impact the decision of choosing between the context and singleton options.

In a distributed application, there would an instance of the context and an instance of the singleton for each VM. So this factor does not impact the decision. (I hope I'm right)

Colin Fletcher had mentioned one thing:
If you are doing lightweight stuff, singleton works, might not be the best practice... If you are doing heavy stuff, context.

I could not understanding what this meant. Could you please elaborate on this.

Your opinions/inputs on the above would be greatly appreciated.

Thanks,
Sheldon Fernandes
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!