0

I'm trying to create a web application for tomcat 7, but my problem is that I want to keep the whole backbone of the application running, so that my servlets can call the functions. Ex. I have my com.example.Main class which house all the instances to things like User managers and such. But instead of getting the main instance redefined on each servlet call, It would get defined once for all the servlets to use.

Best Regards, - Roe

  • So you have one class which has a load of methods defined on it, and you want to access it from a number of servlets, but you don't want to do `Main main = new Main()` in each servlet? – DaveH Aug 05 '14 at 11:43
  • Yes, as defining said main and initializing it takes a lot of time – ImThatPedoBear Aug 05 '14 at 11:50

2 Answers2

1

As far as I understand, you want a singleton. Check this answer for implementation.

But note that singletons are "evil". A more webapp approach is to not have it as singleton, but initialize it once in a ContextLoaderListener and then put it as a ServletContext attribute. Then each servlet can obtain it by getting it from the servlet context.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

I agree with Bozho - you seem to be talking about a Singleton and I share his reservations about using them.

If you do implement it as a singleton, or use Bozho's suggested solution, it is important for you to understand that there will be only one instance of the class, potentially being used by many servlets at the same time. As a result, it is your responsibility to make sure that the class is thread safe, or your application will produce unreliable results.

DaveH
  • 7,187
  • 5
  • 32
  • 53