Monday, July 26, 2021

How Do You Stop a Java Program Gracefully?

Sometimes you may want to stop your java program using SIGINT hitting your CTRL+C. For example, your program may be doing something important, e.g., opening a server socket and waiting on a port or doing some background work on a thread pool. You want to stop it gracefully, shutting down your socket or the thread pool. For such scenarios, what you can do is add a shutdown hook to the java runtime. The following code demonstrates precisely that:

Java
 
package com.bazlur;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Day008 {
  public static void main(String[] args) {
    var executorService = Executors.newSingleThreadExecutor();
    executorService.submit((Runnable) () -> {
      while (true) {
        doingAStupendousJob();
      }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      try {
        executorService.shutdown();
        if (executorService.awaitTermination(100, TimeUnit.MILLISECONDS)) {
          System.out.println("Still waiting 100ms...");
          executorService.shutdownNow();
        }
        System.out.println("System exited gracefully");
      } catch (InterruptedException e) {
        executorService.shutdownNow();
      }
    }));
  }

  private static void doingAStupendousJob() {
    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}




from DZone.com Feed https://ift.tt/36Yld6u

No comments:

Post a Comment