Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an inverse equivalent to the Java Runtime ShutdownHook i.e. StartupHook?

I am looking for a general inverse equivalent of the ShutdownHook in Java Runtime i.e. something like a StartupHook where certain custom warmup or setup code can be executed when the JVM first starts up.

I am aware of alternatives like the use of ServletContexts etc. on the startup of Servlet Containers, or such similar features in other frameworks like Spring etc. But these are not what I'm looking for. I am looking for a general JVM solution, if one is available.

Please let me know if the whole idea of a StartupHook would be inadvisable for the JVM and why.

Update: After going through all the answers provided (thanks everyone), it seems that the closest to what I'm looking for is Java Agents.

Although it would be nice (from an ease-of-use point of view but probably not from a security point of view) if the JVM allows me to do something like this:

  1. Write a class that implements StartUpHook with only one method - void preMain()
  2. Put that class into a jar file and put that jar into the classpath or the JRE extensions directory
  3. When JVM starts up, it looks for all classes in the classpath that implements StartUpHook and then calls its preMain() method.
like image 488
tsaixingwei Avatar asked Sep 03 '25 06:09

tsaixingwei


1 Answers

There is no startup hook in Java. Your choices are (in the order I would recommend them).

  • Use a startup callback feature of the framework you're running in (i.e. Servlets, Spring, etc). This would also include simply having whoever is writing the main method give you a callback.
  • Wrap the main(String[]) method with your own main(String[]) method and then delegate after calling your main from the commandline.
  • Create a java agent library with a Premain-Class definition in your jar manifest then add the agent to the JVM on the command line.

The last two options require you to add or changes things on the command-line.

like image 80
Dev Avatar answered Sep 04 '25 21:09

Dev