Skip to content

Instantly share code, notes, and snippets.

@OlivierLD
Last active February 12, 2024 23:34
Show Gist options
  • Save OlivierLD/74b4642549c9ab81c579acd0e5316642 to your computer and use it in GitHub Desktop.
Save OlivierLD/74b4642549c9ab81c579acd0e5316642 to your computer and use it in GitHub Desktop.
Manage Ctrl-C from Java

Ctrl-C from Java

This shows how to manage a Ctrl-C interrupt from a Java program.
Look into the synchonized blocks...

package oliv.interrupts;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;
public class CtrlCGood {
/**
* How to do it correctly
*/
public static void main(String...args) {
final Thread itsMe = Thread.currentThread();
AtomicBoolean keepWorking = new AtomicBoolean(true);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("\nOops! Trapped exit signal...");
synchronized (itsMe) {
// itsMe.notify();
keepWorking.set(false);
try {
itsMe.wait(); // Give the main thread time to finish...
System.out.println("... Gone");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}));
System.out.println("Starting... Ctrl-C to stop.");
try {
synchronized (itsMe) {
// itsMe.wait();
while (keepWorking.get()) {
System.out.printf("Still at work, at %s...\n", new Date());
itsMe.wait(1_000L);
}
}
System.out.println("Ok, ok! I'm leaving! (doing some cleanup first, 5s...)");
// This stuff takes time
Thread.sleep(5_000L);
System.out.println("Done cleaning my stuff!");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("Bye!");
synchronized(itsMe) {
itsMe.notify(); // Unlock the shutdown hook.
}
System.out.println("Everyone's done now.");
}
}
package oliv.interrupts;
public class CtrlCGood2 {
/**
* How to do it correctly
*/
public static void main(String...args) {
final Thread itsMe = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("\nOops! Trapped exit signal...");
synchronized (itsMe) {
itsMe.notify();
try {
itsMe.join();
System.out.println("... Gone");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}));
System.out.println("Starting... Ctrl-C to stop.");
try {
synchronized (itsMe) {
itsMe.wait(); // This is the "work" this class is doing.
}
System.out.println("Ok, ok! I'm leaving!");
// This stuff takes time
Thread.sleep(5_000L);
System.out.println("Done cleaning my stuff!");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("Bye!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment