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

  • Detecting Bugs and Vulnerabilities in Java With SonarQube
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • AI Agents in Java: Architecting Intelligent Health Data Systems
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI

Trending

  • Spec-Driven Integration: Turning API Sprawl Into a Governed Capability Fleet for AI
  • Architecting Autonomous Agents: A Deep Dive into Azure AI Foundry Agent Service
  • Security Readiness Checklist: From AI Threats to Software Supply Chain Defense
  • How AI Is Rewriting the Rules of Software Security: Machine-Speed Delivery, Shifting Risk, and New Control Points
  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.6K 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

  • Detecting Bugs and Vulnerabilities in Java With SonarQube
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • AI Agents in Java: Architecting Intelligent Health Data Systems
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI

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