Runtime.getRuntime().addShutdownHook(new Thread()
{
    @Override
    public void run()
    {
        updateZonas();
        db.close();
    }
});

This works for any Java application(Swing/AWT/Console)

Answer from Santhosh Kumar Tekuri on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 14932897 › onexit-in-jbpm-5-4-human-task
jboss7.x - onExit in jBPM 5.4 Human Task - Stack Overflow
I'm using jBPM 5.4 with MsSql. It is working fine. I have simple workflow from START ----> TASK A ----------> TASK B --------> STOP I'm trying to access such an workflow from Servlets When i ex...
Top answer
1 of 2
1

You do not want to use File.deleteOnExit(): your web application should run for months without exiting the JVM, right? Instead, you need to clean-up after yourself properly.

Use File.delete() and check the return status (it returns a boolean: check it). If that returns false, figure out why that's happening. For instance, if you are on Windows, there are some (IMO foolish) restrictions on deleting files that are opened by a live process -- including the process trying to delete them. So, if you have another thread that has a file handle to the file you are trying to delete, you are not going to be able to delete the file.

So, what is holding-open that file lock? Find that and fix it. Specifically, make sure that you have properly-closed all your file handles (did you use finally blocks? If no, you're doing it wrong) and that you aren't trying to do something silly like dynamically-generate a file, save it to the disk, have Tomcat serve it using the DefaultServlet, and then delete the file.

If you can't manage to make the file-deletion work synchronously, then maybe try asynchronous deletion: keep a queue of files to delete (maybe in the application scope) and process them every few minutes. Just try to delete each one and, if the deletion succeeds, remove it from the queue. If the queue exceeds some size, automatically send an email to an administrator to complain about the size of the queue.

2 of 2
0

Have you tried below steps in the same web app?
- Read existing files in temp folder
- Delete all files(if there any) which are created earlier.
- Now start stuff's which creates new temp files

🌐
Oracle
docs.oracle.com › en › java › javase › 21 › core › managing-processes-asynchronously-onexit-method.html
Handling Processes When They Terminate with the onExit Method
October 20, 2025 - Exit 12401, status 0 ... have run the method specified by the thenAccept method). If you want to wait for a process to terminate before proceeding with the rest of the program, then call onExit().get():...
🌐
GeeksforGeeks
geeksforgeeks.org › java › stackoverflowerror-in-java-with-examples
StackOverflowError in Java with examples - GeeksforGeeks
July 12, 2025 - In amidst of this process, if JVM runs out of space for the new stack frames which are required to be created, it will throw a StackOverflowError. For example: Lack of proper or no termination condition.
Find elsewhere
🌐
GitHub
github.com › openjdk › jdk › blob › master › src › java.base › share › classes › java › lang › ProcessHandleImpl.java
jdk/src/java.base/share/classes/java/lang/ProcessHandleImpl.java at master · openjdk/jdk
// Increase the total stack size to avoid potential stack overflow. int debugDelta = "release".equals(System.getProperty("jdk.debug")) ? 0 : (4 * 4096); final long stackSize = Boolean.getBoolean("jdk.lang.processReaperUseDef...
Author   openjdk
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › lang › Process.html
Process (Java SE 9 & JDK 9 )
This implementation may consume a lot of memory for thread stacks if a large number of processes are waited for concurrently. External implementations should override this method and provide a more efficient implementation. For example, to delegate to the underlying process, it can do the following: public CompletableFuture<Process> onExit() { return delegate.onExit().thenApply(p -> this); }
🌐
Edureka
edureka.co › blog › system-exit-in-java
Exit function in Java | System.exit() Method with Example | Edureka
November 29, 2022 - Exit function in Java exits the current program by terminating Java Virtual Machine. System.exit() method calls the exit method in class Runtime.
Top answer
1 of 3
2

ProcessImpl.java on destroy method call native function terminateProcess:

public void destroy() { terminateProcess(handle); }

private static native void terminateProcess(long handle);

terminateProcess is platform dependent and for Windows you can find sources here. It's just call Windows TerminateProcess function (link to this function was in previously answer or you can google it) with uExitCode=1 - thats why exit code of destroyed process is 1.

In linux looks like is used something similar to this. And as proof next code return 143 in ubuntu, that correspond to SIGTERM (https://stackoverflow.com/a/4192488/3181901):

public static void main(final String[] args) throws IOException, InterruptedException {
    final Process process = Runtime.getRuntime().exec(args[0]);
    process.destroy();
    Thread.sleep(1000);
    System.out.println(process.exitValue());
}
2 of 3
1
  1. Why would it show a problem? You're trying to destroy a process that was already destroyed. The specification of Process.destroy() doesn't say what happens if there was nothing to destroy, so it is logical (I suppose) to assume that if there's nothing to destroy, then there's nothing to complain about. Compare with Thread.join(), which doesn't just die if the thread has already ended.

  2. The only way to kill a process is to send it a signal. On some OS's, there are other, more "violent" ways (on some platforms, for example, it is possible to simply remove the process from the OS's list of running processes. Results are undefined and it usually ends ugly), but at least with platforms that I know of, it's really all about sending signals.

  3. Possible, indeed, that it's because it takes time to invoke Thread.sleep(). Try increasing the timeout value.

Top answer
1 of 6
36

Add shutdown hook. See this javadoc.

Example:

public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            System.out.println("In shutdown hook");
        }
    }, "Shutdown-thread"));
}
2 of 6
8

Since you are using Swing. When you close your application (by pressing the close button), you could simply hide your frame. Run the method you would want which creates the file and then exit the Frame. This would result in a graceful exit. Should there be any errors/exceptions, you can log that into a separate file.

Here is the code

package test;

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;

public class TestFrame extends JFrame{

    public TestFrame thisFrame;

    public TestFrame(){
        this.setSize(400, 400);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    }

    public static void main(String[] args){
        TestFrame test = new TestFrame();
        test.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentHidden(ComponentEvent e) {
                System.out.println("Replace sysout with your method call");
                ((JFrame)(e.getComponent())).dispose();
            }
        });
    }

}

Please be aware of using shutdown hooks. As given in the Javadoc, it states that

When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook

Top answer
1 of 16
479

Parameters and local variables are allocated on the stack (with reference types, the object lives on the heap and a variable in the stack references that object on the heap). The stack typically lives at the upper end of your address space and as it is used up it heads towards the bottom of the address space (i.e. towards zero).

Your process also has a heap, which lives at the bottom end of your process. As you allocate memory, this heap can grow towards the upper end of your address space. As you can see, there is a potential for the heap to "collide" with the stack (a bit like tectonic plates!!!).

The common cause for a stack overflow is a bad recursive call. Typically, this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself forever. Or when the termination condition is fine, it can be caused by requiring too many recursive calls before fulfilling it.

However, with GUI programming, it's possible to generate indirect recursion. For example, your app may be handling paint messages, and, whilst processing them, it may call a function that causes the system to send another paint message. Here you've not explicitly called yourself, but the OS/VM has done it for you.

To deal with them, you'll need to examine your code. If you've got functions that call themselves then check that you've got a terminating condition. If you have, then check that when calling the function you have at least modified one of the arguments, otherwise there'll be no visible change for the recursively called function and the terminating condition is useless. Also mind that your stack space can run out of memory before reaching a valid terminating condition, thus make sure your method can handle input values requiring more recursive calls.

If you've got no obvious recursive functions then check to see if you're calling any library functions that indirectly will cause your function to be called (like the implicit case above).

2 of 16
74

If you have a function like:

int foo()
{
    // more stuff
    foo();
}

Then foo() will keep calling itself, getting deeper and deeper, and when the space used to keep track of what functions you're in is filled up, you get the stack overflow error.

🌐
Scaler
scaler.com › home › topics › java › exit method in java
Exit Method in Java - Scaler Topics
April 3, 2024 - Learn about exit method in Java. Scaler Topics also explains the syntax, parameters, and return value along with the goto method in Java.
🌐
Stack Overflow
stackoverflow.com › a › 2469673
We cannot provide a description for this page right now
🌐
Yourkit
yourkit.com › docs › java-profiler › latest › help › onexit.jsp
YourKit Java Profiler help - Callback onExit()
Fully featured low overhead profiler for Java EE and Java SE platforms. ... Easy-to-use performance and memory .NET profiler for Windows, Linux and macOS. ... Secure and easy profiling in cloud, containers and clustered environments. ... Performance monitoring and profiling of Jenkins, Bamboo, TeamCity, Gradle, Maven, Ant and JUnit. ... Callback method onExit() can be used instead of two separate callbacks onReturn() and onUncaughtException().