Make java exit out of current program - java

How do I make java quit the program when it is triggered? I have tried pretty much everything I can do, but I just can't make it quit.

You can use System.exit(0); where 0 is the exit code. This works on all platforms (including android).
Here is a link to the official documentation if you require further reading:
Oracle Documentation

public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n)

Related

Native implementation of Process.waitFor method

I have used a method waitFor of Process class, to execute some UNIX command. The command is executing successfully but it is returning 2, that according to convention means abnormal termination.
I googled and found that it depends on "source code of the program that is outputting this exit code". So I tried to find the source code for waitFor method, I came to know that it is a native method and defined in ProcessImpl class.
public native int waitFor();
So I searched for native implementation of this method from here. But I did not found the file that provide me the native implementation of waitFor method.
My question is how to find the file in which native implementation of this method is written?
The source code mentioned refers to the source of the program you are executing with your Process object.
In your case, it is the UNIX command you are executing using the Process that is terminating with exit code 2, not the waitFor() method itself.
So to answer your actual question, the answer is: Within the source code of the JDK you are using, for example here is the source for OpenJDK6.
However, if your actual question is "Why is waitFor() returning a non zero exit code", then the answer is: The Process you are executing with Java has returned a non zero exit code, and the Process object is informing you via the return of the waitFor() method

Why do we have exit codes in Java?

In Java, we use System.exit(int) to exit the program.
The reason for an "exit value" in C was that the exit value was used to check for errors in a program. But in Java, errors are reflected by an Exception being thrown, thus they can be handled easily. So why do we have exit values in Java at all?
exit values are returned to the calling program e.g. the shell. An Exception cannot be caught by an external program.
BTW When you throw an Exception it is caught by that thread or that thread dies, the finally blocks are still called for that thread. When you call System.exit(), all threads stop immediately and finally blocks are not called.
For the same reason.
Exit codes are exclusively used by parties and applications outside of the program for debugging and handling purposes. A super-application can definitely handle a return code better than trying to parse a stack trace.
Also, if you are creating an application for an end-user, you would much rather exit gracefully from your app than post a bunch of stack trace information, for a couple of reasons: one, you will just be scaring them with lots of crazy-looking techno-gibberish, and two, stack traces often reveal sensitive and confidential information about the way the program is structured fundamentally (giving a potential attacker more knowledge about the system).
For a real-world example, I was working on a Java Batch program which used exit codes for its jobs. A user could see whether the job executed successfully or not based on whether the exit code was "0". If it was anything else, they could contact technical support, armed with the additional information of the exit code, and the help desk would have all the necessary information based on that exit code to help them out. It works much nicer than trying to ask a non-technical end-user, "Okay, so what Exception are you getting?"
exit values are returned to the callers to signal the successful or insuccessful completion of the program. The caller may not be able to catch the exception and handle it accordingly.
For eg. 0 exit value means successful completion whereas non-zero return value means some error in execution.
Also, System.exit() will make all the threads in the application to stop at that point itself.
Long story short, Exit codes are simplified signals to the user who encounters an exception while running a Java program. Since we assume that most of the users do not understand stack trace data of an exception, these simple non zero custom code will tell them that something is wrong and this should be reported to the vendor. So the vendor gets the code and he knows the stack trace associated with that code and tries to repair the system. This is an abstraction provided by the programmers so that users don't have to read and report voluminous stack traces. A very good analogy here is the getErrorCode() method in SQLException class. This method also closes the current JVM that is running on the client machine. This implies that this terminates all the threads that are in the JVM. This method calls the exit method in the class Java.lang.Runtime. If you go to the documentation of this method, you will understand how virtual machine is shut down.
This is the link
http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exit%28int%29

Interpreting JavaScript in Java with Rhino: pausing/resuming scripts

I'm using the javax.script.* package of the JDK. Specifically, I'm using the JavaScript engine, which, from what I've read, seems to be based on a Mozilla-developed JavaScript-in-Java interpreter called Rhino.
What I'm hoping to accomplish is to basically have my JavaScript able to "pause" itself at a certain point in the code (say, halfway through a function call) and only resume itself later when Java allows it to do so.
To illustrate what I mean, imagine this JavaScript code:
function myJSFunction() {
print("Hello ");
mysteriousPauseFunction(); // this is the part I'm wondering about. basically, the script should break here and resume later at Java's discretion...
// upon reaching this comment, we know now that Java has told JavaScript that it's okay to resume, so the next line will now be executed...
print("world");
}
If the "pausing"/"breaking" part involves binding a Java function and passing it a reference to the current ScriptEngine or whatever, that's cool with me. I'm thinking that's what this will probably involve: pausing the JavaScript from within Java.
I did some googling and found that the keyword here appears to be "continuations." From what I can tell, Rhino only supports continuations in interpreted mode (versus compiled mode), which I see is accomplished by setting the "context" to -2. Since the built-in JDK ScriptEngine doesn't seem to mention anything about contexts (or maybe I'm missing it), does this mean I have to download and use Mozilla's Rhino library directly instead?
And are Rhino continuations what I need to accomplish this? I've found a useful tutorial on Rhino continuations, but after reading through it, I'm not 100% sure if this is going to be able to accomplish what I described above. If this is what I'm looking for, then my follow-up question is about the "serialization" mentioned: does this mean that when I resume my script, all variables will have been unset unless I serialize them?
Update: It looks like this IS possible with Rhino. Here's what I have so far in my JavaScript; after the code, I'll explain what it does...
var end = new Continuation();
function myJSFunction()
{
print("Hello ");
var kont = new Continuation();
storePause(script, kont); // script is previously bound by Java into the JavaScript. it is a reference to the script itself.
end();
print("world");
}
My "storePause()" function is a Java function which I have written, and it is bound to the JavaScript, but right now, it doesn't do anything. My next goal will be to flesh out its code such that it stores the continuation and script information as Java objects, so that Java can resume the script later.
Right now, what it's doing is pausing/"breaking" the script after "Hello " is printed but before "world" is printed, so this proves to me that it is possible to pause a script this way.
So, all that I should have left to figure out at this point is how to resume a continuation. Note that the above works using the JDK scripting engine by default (I haven't needed to worry about interpreted mode vs compiled mode at this point -- it seems to default to interpreted mode), but it looks like the process of resuming a script will require Mozilla's Rhino library.
Alright, it took me many hours of digging through documentation, tutorials, and examples, and also posting on here and on the Rhino Google Group, but I've managed to compile a working solution. Since there seems to be no complete example, I'll post my findings here for anyone who stumbles across this in the future.
Actually, my findings are probably too long to post here, so I decided to write up a tutorial on my blog:
Tutorial: Continuations in Mozilla Rhino (a JavaScript interpreter for Java)
Hope that helps someone. As far as I know, this is the only complete Rhino tutorial that shows how to do all of the following: initialize Rhino, load a script from a JavaScript (*.js) file, automatically bind all of the functions in a particular Java class (e.g. ScriptFunctions) as global functions in JavaScript, and finally call a JavaScript function and handle continuations for that call.
Basically, the problem was that I needed to first download the Mozilla Rhino source code (because the version packed in with the JDK is outdated and doesn't support continuations), rewrite all of my code to use the official Rhino package's syntax (it is very different from JDK's ScriptingEngine syntax), write a Java function that throws a ContinuationPending exception and bind it to JavaScript so JavaScript can call it (because throwing a ContinuationPending directly from JavaScript results in a JavaScriptException being thrown, not a ContinuationPending being thrown, and even trying to call getCause() on that JavaScriptException results in null), and then in my Java code that calls my JavaScript function ("myJSFunction" in my original example), have try/catch blocks to check for a ContinuationPending (which is an exception), and then use that ContinuationPending
later to resume the script.
Phew. It was tough, but it's all worth it now.
You didn't explain why you were doing this, but I was emulating a program that interacts with an end user, like this:
print('Hello!');
a=Number(input('enter a number'));
b=Number(input('and another number'));
print('the sum of '+a+' plus '+b+' is '+(a+b))
I've got it working just by creating a print and an input function in javascript that checks for program state.
you can see a demo here.
it's all written in javascript so you can look at the source code with any browser.
Hope it helps
You could use wait/notify:
public final class Pause {
private final Object lock = new Object();
public void await() throws InterruptedException {
synchronized (lock) {
lock.wait();
}
}
public void resumeAll() {
synchronized (lock) {
lock.notifyAll();
}
}
}
Usage:
final Pause pause = new Pause();
class Resumer implements Runnable {
#Override public void run() {
try {
Thread.sleep(5000);
pause.resumeAll();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
new Thread(new Resumer()).start();
SimpleBindings bindings = new SimpleBindings();
bindings.put("pause", pause);
String script = "print('Hello, ');\n"
+ "pause.await();\n"
+ "println('ECMAScript!');\n";
new ScriptEngineManager().getEngineByName("ECMAScript")
.eval(script, bindings);
This is a relatively simplistic solution as you don't mention any other constraints. wait() causes the thread to block, which would not be acceptable in all environments. There is also no easy way to identify what threads are waiting on the Pause instance if you want to run scripts concurrently.
Note: the InterruptedException on await() should be handled either by the caller or by doing something more sensible in await().

How to quit a java app from within the program

What's the best way to quit a Java application with code?
You can use System.exit() for this purpose.
According to oracle's Java 8 documentation:
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n) is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
System.exit(0);
The "0" lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1);, or with another non-zero number corresponding to the specific error.
Also, as others have mentioned, clean up first! That involves closing files and other open resources.
System.exit(int i) is to be used, but I would include it inside a more generic shutdown() method, where you would include "cleanup" steps as well, closing socket connections, file descriptors, then exiting with System.exit(x).
System.exit() is usually not the best way, but it depends on your application.
The usual way of ending an application is by exiting the main() method. This does not work when there are other non-deamon threads running, as is usual for applications with a graphical user interface (AWT, Swing etc.). For these applications, you either find a way to end the GUI event loop (don't know if that is possible with the AWT or Swing), or invoke System.exit().
Using dispose(); is a very effective way for closing your programs.
I found that using System.exit(x) resets the interactions pane and supposing you need some of the information there it all disappears.
I agree with Jon, have your application react to something and call System.exit().
Be sure that:
you use the appropriate exit value. 0 is normal exit, anything else indicates there was an error
you close all input and output streams. Files, network connections, etc.
you log or print a reason for exiting especially if its because of an error
The answer is System.exit(), but not a good thing to do as this aborts the program. Any cleaning up, destroy that you intend to do will not happen.
There's two simple answers to the question.
This is the "Professional way":
//This just terminates the program.
System.exit(0);
This is a more clumsier way:
//This just terminates the program, just like System.exit(0).
return;
Runtime.getCurrentRumtime().halt(0);
System.exit() will do what you want. But in most situations, you probably want to exit a thread, and leave the main thread alive. By doing that, you can terminate a task, but also keep the ability to start another task without restarting the app.
System.exit(ABORT);
Quit's the process immediately.
This should do it in the correct way:
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowListener() {
#Override
public void windowClosing(WindowEvent e) {
if (doQuestion("Really want to exit?")) {
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.dispose();
}
}

Setting default System.exit codes in Java?

I have a C# app that runs a jar file and uses the System.exit code as a return value. A console window is displayed as a part of this jar, and if the user closes it (thereby terminating the jar) it returns an exit code of 143. The problem is that 143 (or any positive integer) could be a valid exit code if the jar completes successfully.
I need a way to manually set the System.exit code to a negative integer. Treating 143 as an exception in the C# app is out of the question.
As in Diego Dias answer,
The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
If you really want to ignore that, and both the Java and the C# apps are in your hand, an easy workaround is to add 1000 to your System.exit return value in Java, when the jar completes.
Your C# application will recognize the successful execution by a return code >= 1000 and subtract it again. 143 is below 1000 and thus an error.
Acording to the java documentation you can use System.exit(int n), so just put a negative number as a parameter, also by convention, a nonzero status code indicates abnormal termination.

Categories