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

StackOverflow https://stackoverflow.com/questions/17936019

  •  04-06-2022
  •  | 
  •  

Domanda

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.
È stato utile?

Soluzione

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.

Altri suggerimenti

What's your use case?

The only reason shutdown hooks are useful is because you do not know when the JVM will shut down. Some piece of code could unexpectedly call System.exit, or all of the windows in a GUI could be closed which would terminate the JVM.

On the other hand, you always know when the JVM will be starting up. Put any code you need to be run at startup in your main method.

Just write a static initializer block in a class you know is going to be loaded at startup.

See http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html.

You must be an agent library and define a pre-main method.

How about using a static block in the java class where main is invoked. static block in this case will act like a start up hook, unless you want to control jvm level parameters

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top