• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton or servlet context attribute  RSS feed

 
D Rog
Ranch Hand
Posts: 472
Linux Objective C Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need an instance of some object serviced all requests. Is it reliable to put it in context instead of defining singleton?
 
SunilRee Gupta
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on your need and the context in which you are using. It seems you can put your that object with Context.For each WebApp your are having only One ServleContext.
 
Pradeep bhatt
Ranch Hand
Posts: 8933
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by D Rog:
I need an instance of some object serviced all requests. Is it reliable to put it in context instead of defining singleton?


How is it more reliable to put in the context?
 
ramprasad madathil
Ranch Hand
Posts: 489
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ofcourse by putting it as a context attribute, it would make your life earier in jsps if you require to access the object properties especially so if you are using technologies like jstl and el which provides transparent scope lookup.
Iam not sure about the singleton even otherwise though.

Where are you accessing it ? In your servlet or jsp's service methods ? Is the singleton object obtained as a local reference in these cases ? If so there is an even chance that it may be gc-ed. (somebody correct me if you know this for wrong).

Application context attributes are specifically used in such cases and I think, may be the best practise to adopt.

cheers,
ram.
 
D Rog
Ranch Hand
Posts: 472
Linux Objective C Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If my singleton stored as an attribute keeps state and somebody removed accidentally or replaced by another copy? It's my concern only. Singleton is quite self protecting, so it isn't easy to destroy or recreate it. That I meant by more reliable. Anyway, attribute looks better for me, so thank all for your input.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!