Shishir Halaharvi
Shishir Halaharvi

Reputation: 3

Gracefully shut down javaagent when application exits

I'm writing a javaagent to monitor applications. It starts up a server and displays the metrics calculated.

How do I configure my agent so that whenever the application is closed, some clean up is performed, and the agent exits? I've looked at shutdown hooks, but they require access to the main method which I do not have.

This is my premain method. I'm using Prometheus's Java library for generating the metrics, and jetty for the server itself.

    Server server = new Server(1234);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    // Expose Promtheus metrics.
    context.addServlet(new ServletHolder(new MetricsServlet()), "/");
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();


    // Start the webserver.
    server.start();
    server.join();

When the application exits, the JVM does not, because my agent is holding it up. I am generating logs from the server, and would like to save whatever data I have and exit, instead of holding up the JVM. I've also looked at byte buddy to transform the main class, but can you add a shutdown hook through it? Is there any other way to do it?

Upvotes: 0

Views: 851

Answers (1)

Ramesh Subramanian
Ramesh Subramanian

Reputation: 1037

This is due to the threads used in the javaagent are not daemon threads. Change these as setDaemon(true);

Upvotes: 1

Related Questions