I am relatively new to Stackoverflow and Java, but I have a little experience in C. I liked the very clean way of C exiting the programs after a malfunction with the 'exit()' function.
I found a similar function System.exit() in Java, what differs from the C function and when should I use a 'System.exit()' best instead of a simple 'return' in Java like in a void main function?
System.exit() will terminate the jvm initilized for this program, where return; just returns the control from current method back to caller
Also See
when-should-we-call-system-exit-in-java ?
System.exit() will exit the program no matter who calls it or why. return in the main will exit the main() but not kill anything that called it. For simple programs, there is no difference. If you want to call your main from another function (that may be doing performance measurements or error handling) it matters a lot. Your third option is to throw an uncaught runtime exception. This will allow you to exit the program from deep within the call stack, allow any external code that is calling your main a programmatic way to intercept and handle the exit, and when exiting, give the user context of what went wrong and where (as opposed to an exit status like 2).
System.exit() may be handy when you're ready to terminate the program on condition of the user (i.e. a GUI application). return is used to return to the last point in the program's execution. The two are very different operations.
Related
Everywhere I look about how to forcefully stop a thread in Java, I see "just do an exit variable check instead, your program is broken if you need to force kill."
I have a rather unique situation though. I am writing a Java program that dynamically loads and runs other Java classes in a separate thread. (No comments about security risks please, this is a very specific use case).
The trouble is, since other people will have written the classes that need to be loaded, there's no way to guarantee they'll implement the stop checking and whatnot correctly. I need a way to immediately terminate their thread, accepting all the risks involved. Basically I want to kill -9 their thread if I need to. How can I do this in Java?
Update: here's a bit more info:
This is actually an Android app
The user code depends on classes in my application
A user class must be annotated with #UserProgram in order to be "registered" by my application
The user also has the option of building their classes right into the application (by downloading a project with the internal classes already compiled into a libraries and putting their classes in a separate module) rather than having them dynamically loaded from a JAR.
The user classes extend from my template class which has a runUserProgram() method that they override. Inside that method, they are free to do anything they want. They can check isStopRequested() to see if I want them to stop, but I have no guarantee that they'll do that.
On startup, my application loads any JARs specified and scans both all the classes in the application and the classes in those JARs to find any classes annotated with the aforementioned annotation. Once a list of those classes is built, it is fed into the frontend where the UI provides a list of programs that can be run. Once a program is selected, a "start" button must be pressed to actually start it. When it is pressed, the button changes to a "stop" button and a callback is fired into the backend to load up the selected class in a new thread and call the runUserProgram() method. When the "stop" button is pressed, a variable is set which causes isStopRequested() to return true.
You can kill -9 it by running in its own process i.e. start with a ProcessBuilder and call Process.destroyForcibly() to kill it.
ProcessBuilder pb = new ProcessBuilder("java", "-cp", "myjar.jar");
pb.redirectErrorStream();
Process process = pb.start();
// do something with the program.
Scanner sc = new Scanner(process.getOutputStream());
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
// when done, possibly in another thread so it doesn't get blocked by reading.
process.waitFor(1, TimeUnit.SECONDS);
if (process.isAlive())
process.destroyForcibly();
Java 8 had Thread.stop(). The problem is that it could only work reasonably for very limited use cases, so limited you were better off using interrupts, and if the code isn't trusted, neither are any good.
There is the deprecated Thread.stop() but don't use it.
There is no way to cleanly terminate another thread without it cooperating.
The thread can be in a state where it allocated some memory, or added some objects to some global state, locked some mutexes, etc. If you kill it at the wrong moment, you risk leaking memory or even causing a deadlock.
It would be possible through JNI, under Windows there is a TerminateThread API that you can call, there is (hopefully) probably a similar thing under Android. The trouble will be getting the thread's native handle, you would need to obtain that when your user "program" is first loaded, probably by calling another JNI method from the thread in question as part of the initialisation process and getting the current thread handle from that.
I have not tried this myself, best case is that this "works" and kills the thread, but it is going to cause that thread to leak resources. Worst case is that it will leave the JVM in an inconsistent state internally, which will probably crash your entire application.
I really think this is a Bad Idea.
A better design, if you want to allow this, is to run your user code in another process and communicate with it via sockets or pipes. This way you can relatively safely terminate the other process if necessary. It's more work, but it's going to be a lot better in the long run.
You shold use Thread.interrupt().
I have a java app which has a menu. One of the menu items is Exit. Which is defined as follows:
item_exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
Another menu item is New, which makes another instance (?) of the same program run in parallel. It is defined as follows:
item_new.addActionListener(new ActionListener() {
MyApp app = new MyApp();
app.start();
}
});
It works as desired except for one problem. It's that when I close one of them, both of them close. The entire app is built on one JFrame object. I don't think changing the default close operation of it will help. I think the issue is with system.exit(0). But, what is the alternative to fix this? I only want the thread I closed to close, not all of them. Thanks.
Creating an object and callings its start() method doesn't make another program run in parallel. It only creates an object, in the same JVM, and executes its start() method, in the same JVM.
System.exit() exits the JVM, so everything running in this JVM stops running.
To make a JFrame invisible, you call setVisible(false) on it. That won't stop the JVM.
System.exit(0); makes the entire Java machine to quit, with everything that is running within. Try not to use this, unless you really need this to happen.
For quitting, perhaps try checking this How to close a Java Swing application from the code
System.exit(0) quits the complete program, not only the current thread. If you want to quit a thread, you have two options: a thread automatically quits as soon as the corresponding Runnables run() method finishes, or you can kill the thread using thread.stop() (just for completeness, shouldn't be used).
Please read the documentation for System.exit(). It specifically states:
Terminates the currently running Java Virtual Machine.
This means the JVM will terminate, and all of your threads with it.
System.exit(0) shuts the whole JVM down.
Your two instances run on the same JVM : you don't fork a process, you just create another instance of your MyApp class. So it is obvious that both "applications" will be killed.
Instead of calling System.exit(0), you should send a termination signal to the JFrame you want to close
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
This way, only that JFrame (or "application") will be killed.
Another option would be to fork a whole new process. For that, I recommend you take a look at the Process class.
Basically, you'll need to change the action of "Exit" so that it's able to detect when there's another "app" currently running ... and to do something plausible in that case. Maybe you alert the user that the other activity hasn't finished yet, and warn him that if he really wants to exit now, the other activity will be abandoned. Maybe you launch the other activity in such a way that it is altogether separate and therefore doesn't care. There are several good alternatives, so this really becomes a design decision on your part: what strategy makes the most intuitive sense for you, and for your users?
I am a beginner in java and I used Delphi for a long time.
When I want to leave a method I need to use the exit() method and in Java I use return.
To abort all subsequent methods I call the abort() method in Delphi. How to do this in Java?
There's no direct support in Java for what you're asking, but in a non-elegant way you could simulate abort's behavior by throwing an exception and catching it wherever you see fit in your code.
Using System.exit(0) would not be the same, that method call will exit your program without any chance to recover along the way.
If you use abort like in this link (http://www.delphibasics.co.uk/RTL.asp?Name=Abort),
i think this functionality is similar with throw see this link
http://www.roseindia.net/java/exceptions/how-to-throw-exceptions.shtml
http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions
In my application which runs user submitted code[1] in separate threads, there might be some cases where the code might take very long to run or it might even have an infinite loop! In that case how do I stop that particular thread?
I'm not in control of the user code, so I cannot check for Thread.interrupted() from the inside. Nor can I use Thread.stop() carelessly. I also cannot put those code in separate processes.
So, is there anyway to handle this situation?
[1] I'm using JRuby, and the user code is in ruby.
With the constraints you've provided:
User submitted code you have no control over.
Cannot force checks for Thread.interrupted().
Cannot use Thread.stop().
Cannot put the user code in a process jail.
The answer to your question is "no, there is no way of handling this situation". You've pretty much systematically designed things so that you have zero control over untrusted third-party code. This is ... a suboptimal design.
If you want to be able to handle anything, you're going to have to relax one (or preferably more!) of the above constraints.
Edited to add:
There might be a way around this for you without forcing your clients to change code if that is a(nother) constraint. Launch the Ruby code in another process and use some form of IPC mechanism to do interaction with your main code base. To avoid forcing the Ruby code to suddenly have to be coded to use explicit IPC, drop in a set of proxy objects for your API that do the IPC behind the scenes which themselves call proxy objects in your own server. That way your client code is given the illusion of working inside your server while you jail that code in its own process (which you can ultimately kill -9 as the ultimate sanction should it come to that).
Later you're going to want to wean your clients from the illusion since IPC and native calls are very different and hiding that behind a proxy can be evil, but it's a stopgap you can use while you deprecate APIs and move your clients over to the new APIs.
I'm not sure about the Ruby angle (or of the threading angle) of things here, but if you're running user-submitted code, you had best run it in a separate process rather than in a separate thread of the same process.
Rule number one: Never trust user input. Much less if the input is code!
Cheers
Usually you have a variable to indicate to stop a thread. Some other thread then would set this variable to true. Finally you periodically check, whether the variable is set or not.
But given that you can't change user code , I am afraid there isn't a safe way of doing it.
For Running Thread Thread.Interrupt wont actually stop as sfussenegger mentioned aforth (thanks sfussenegger recollected after reading spec).
using a shared variable to signal that it should stop what it is doing. The thread should check the variable periodically,(ex : use a while loop ) and exit in an orderly manner.
private boolean isExit= false;
public void beforeExit() {
isExit= true;
}
public void run() {
while (!isExit) {
}
}
In the case of languages with a C-like syntax, we declare the main() method to return an int or float value (or void). Is it possible to declare a non-void return type from main() in Java? If not, then why not? Does this mean that a Java program doesn't return any value to the OS?
The main() method must indeed have a void return type. From the Java Language Specification on "Execution - Virtual Machine Start-Up" (§12.1.4):
The method main must be declared
public, static, and void. It must
accept a single argument that is an
array of strings.
It goes on to describe when a program exits in "Execution - Program Exit" (§12.8):
A program terminates all its activity
and exits when one of two things
happens:
All the threads that are not
daemon threads terminate.
Some thread
invokes the exit method of class
Runtime or class System and the exit
operation is not forbidden by the
security manager.
In other words, the program may exit before or after the main method finishes; a return value from main would therefore be meaningless.
If you want the program to return a status code, call one of the following methods (note that all three methods never return normally):
System.exit(int status) - Equivalent to Runtime.getRuntime().exit(status)
Runtime.exit(int status) - Terminates the currently running JVM by initiating its shutdown sequence (run all registered shutdown hooks, and uninvoked finalizers, if necessary). Once this is done the JVM halts.
Runtime.halt(int status) - Forcibly terminates the currently running JVM.
Of the three, System.exit() is the conventional and most convenient way to terminate the JVM.
This is an interesting discussion on velocityreviews on the same topic:
Highlight:
Incidentally, this is considered bad style in C and C++ just because
it's the wrong signature for main, not for any universal reason
independent of programming languages. It's one of those things that is
not really supposed to work, but might on your implementation.
In Java, the reason main returns void is threads. C and C++ were both
designed as languages before multithreading was a widely known
technique, and both had threads grafted onto them at a later date. Java
was designed from the beginning to be a multithreaded environment, and
frankly, it would be unusual to write any non-trivial Java application
that doesn't use more than one thread. So the idea that a program moves
linearly from the beginning to the end of main is a bit outdated.
written by
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
The reason for the main method having void as return type is that once main finishes, it doesn't necessarily mean that the entire program finished. If main spawns new threads, then these threads can keep program running. The return type of main doesn't make much sense at this point.
For example, this is very common in Swing applications, where the main method typically starts a GUI on the Swing thread, and then main finishes... but the program is still running.
You can return an int with System.exit().
Returning anything other than an integer doesn't make much sense, as the OS expects an integer. In case nothing is returned the default is 0, which means OK. Other values typically are used to signal errors or special conditions.