DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j
  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j

Trending

  • MuleSoft MCP and A2A in Production: What 17 Recipes Reveal
  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  • Multi-Scale Feature Learning in CNN and U-Net Architectures
  • Monitoring Spring Boot Applications with Prometheus and Grafana
  1. DZone
  2. Coding
  3. Java
  4. How Do You Stop a Java Program Gracefully?

How Do You Stop a Java Program Gracefully?

This short article provides readers with a way to gracefully stop a Java program in case your program may be doing something important.

By 
A N M Bazlur Rahman user avatar
A N M Bazlur Rahman
DZone Core CORE ·
Jul. 26, 21 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
7.7K Views

Join the DZone community and get the full member experience.

Join For Free

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();
    }
  }
}


Java (programming language)

Published at DZone with permission of A N M Bazlur Rahman. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j
  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook