I am developing a java standalone application where it has to upload batch of files to rest api. I want to stop the application whenever I needed from the command prompt but if the application is in the process of uploading a file it has to complete that and has to stop before starting to upload another file.
3 Answers
It cannot stop any time you wish because (I assume) your program runs on a single thread, and thus, must complete every task in the order it is given.
When uploading a list of files, you can provide some kind of listener in the front on one thread while the files upload in the background. When Thread1 recieves the information that it needs to quit, it could then set some kind of global boolean that thread 2 checks before it starts uploading the second file.
Making the upload process a background thread allows you to modify the program in the process.
If you were looking for documentation on gracefully exiting the program in general, it can be found here: http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exit%28int%29

- 29
- 4
You could do a quick check on an isUploading flag in your application's exit code JVM shutdown hook. If false, continue with the exit. If true, wait for the upload process to complete or timeout.

- 1,085
- 1
- 8
- 24
public class Main {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
r.addShutdownHook(new ShutdownHook());
while(Flag.flag){
System.out.println("Application is still running......");
}
if(!Flag.flag) {
System.out.println("goin to exit the application");
Flag.shutdownFlag = false;
return;
}
}
}
public class Flag {
public static boolean flag = true;
public static boolean shutdownFlag = true;
}
public class ShutdownHook extends Thread {
public void run() {
System.out.println("Shutdown hook is initiated");
Flag.flag = false;
while (Flag.shutdownFlag) {
System.out.println("Waiting for application to complete the task..");
}
}
}
I am running the jar in command prompt. As soon as we want to stop the application we can just give ctrl+c in command prompt.

- 1
- 5