4

I am creating a client library for an API endpoint using Unirest to simulate GET and POST requests. Once the program finishes, the following code must be called in order to terminate the current thread.

Unirest.shutdown(); // must be called in order to clear the high CPU consuming thread 

Is there any possible way implicitly call this in my client library at the end of the program's execution?

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70

1 Answers1

1

Yes - your best option is likely a Shutdown Hook. It will be called/executed when the JVM is terminating. As an example:

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        System.out.println("JVM shutting down, closing Unirest");
        Unirest.shutdown();
    }
}));

You should ideally call the addShutdownHook() method as soon as possible, after you have started the Unirest service.

Craig Otis
  • 31,257
  • 32
  • 136
  • 234
  • This looks good but is there a way to make this code implicitly executed after importing my client library? – Malik Brahimi Jul 29 '15 at 17:00
  • I'm not sure I follow. Is your code responsible for starting the Unirest client in your library? If so, that's where you should be adding your shutdown hook. You can't (shouldn't) magically start executing code unless called *by* the project that's making use of your library. – Craig Otis Jul 29 '15 at 17:03
  • Yes, but users can create several requests which require only one shutdown. Thus it is pointless to create several shutdowns in each of my library's methods. – Malik Brahimi Jul 29 '15 at 17:05
  • In that case, it might be worth maintaining some kind of singleton or manager class that is responsible (with a boolean flag, or similar) for keeping track of whether you've installed the hook or not. So no matter how many times you call this `UnirestManager.getOrCreateUnirest()` method, it will only install the shutdown hook once. – Craig Otis Jul 29 '15 at 17:09
  • Is there a way to check using the `Runtime` or just go with a boolean? – Malik Brahimi Jul 29 '15 at 17:14
  • There's no way to check from the Runtime. What would you ask it? "Do you have a Thread that looks like this?" It's a complicated question for the Runtime to answer. You can install as many shutdown hooks as you want, so there's no easy way to ask the Runtime if it has a specific variety. You should internally (in your library) keep track of whether the hook has been installed yet. – Craig Otis Jul 29 '15 at 17:16
  • Thread will invoke the Runnable.run that you provided. However, you can just override Thread.run instead. Then you don't need to instantiate a Runnable. – H2ONaCl Oct 06 '16 at 20:30