7

Imagine that I want to ensure that class is instantiated upon deployment in Tomcat of the war it is contained in.

For example a class has a static initializer that launches a thread that periodically prints the CPU usage. I need this class to start monitoring as soon as the Tomcat loads the war.

Is there a way to do this without having to call a Servlet that has a reference to this class so the ClassLoader loads it and the static initializer is executed?

daniel sp
  • 937
  • 1
  • 11
  • 29
  • 3
    Use a servlet context listener to do that job. Check https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html – ernest_k May 16 '18 at 14:40
  • @ErnestKiwele I thought about that too, but I just wonder if there are callbacks like `onExplode` or something, I like the question! – Eugene May 16 '18 at 14:49
  • The life-cycle of the application starts too late for that. If you need to do stuff that early, maybe you should embed the container. – ernest_k May 16 '18 at 14:53
  • Hi Ernest, your solution works fine for me. If you create a reply instead of a comment, I'll set it as valid. Tks. – daniel sp May 16 '18 at 15:10

1 Answers1

0

As stated in the comment above, you can use a servlet context listener to do that job. This answer shows how to implement the class.

Marcus K.
  • 980
  • 11
  • 26