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

  • Dynamic Arrays, Spill, and LET: What Changed in Excel and Why It Matters for Java Applications
  • Why I Don't Want an LLM Generating Java Business Logic
  • Pragmatic Premature Optimization
  • Running Sentiment Analysis Inside Neo4j With a Java Plugin

Trending

  • Document SDK vs Basic PDF Library: What Growing Teams Should Know
  • How to Design a Multi-Agent AI Framework in Python for Enterprise LLM Workflows
  • Architecting Trust: Agentic Microservice Testing Strategies in the Era of Non-Deterministic AI
  • Memory-First Indexes in SQL Server 2025: Redefining Performance for Hybrid Workloads
  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.9K 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

  • Dynamic Arrays, Spill, and LET: What Changed in Excel and Why It Matters for Java Applications
  • Why I Don't Want an LLM Generating Java Business Logic
  • Pragmatic Premature Optimization
  • Running Sentiment Analysis Inside Neo4j With a Java Plugin

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