I am asking because if it is not, it can be abused as synchronizations mechanism. I am asking about Java.
I'm not sure what you mean by "can be abused as synchronizations mechanism" - that doesn't make sense.
Exceptions are per thread - when an exception is thrown, the current thread's execution jumps to the place where the exception is caught. If it's not caught at all, the thread dies. Other threads are not affected.
JLS 11.3.2 Handling Asynchronous Exceptions
Most exceptions occur synchronously as a result of an action by the thread in which they occur, and at a point in the program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a program.
Proper understanding of the semantics of asynchronous exceptions is necessary if high-quality machine code is to be generated.
Asynchronous exceptions are rare. They occur only as a result of:
An invocation of the stop methods of class Thread or ThreadGroup
An internal error in the Java virtual machine
So no, while rare, not all Exception handling is synchronous.
No, it's synchronous.
Try stepping through your code with a debugger, you'll see that it executes line after line, and will not continue if you break inside the catch.
Exceptions occur during the execution of a thread. It does not make sense to have an asynchronous catch because the thread has to handle the exception. It cannot proceed till the exception is caught and taken care of. If the exception is not caught or thrown, the thread does not know what it has to do and simple dies and the program may/may not misbehave.
A thread throwing an exception and then proceeding without waiting for the catch does not make sense.
To answer your question, no catching is not asynchronous for all practical purposes.
Related
When working with threads in Java, dealing with InterruptedException seems to be a particular thorn in my side. I appreciate the fact that it's thrown when my threads are terminated, and thus offers me a chance to cleanup. What seems odd to me is that it's not an unchecked exception.
This creates the following problems:
a) If I want to use an existing framework in my threaded app, I'm forced to convert it to an exception the framework interface accepts. Thus the framework generally misinterprets it instead of either cleaning up or propagating it as it should.
b) Unless InterruptedException is rigorously declared for every call in the stack (and it's usually not because of a) ), it's difficult to cleanly shutdown.
If InterruptedException were instead unchecked, it seems that it would have a much higher likely hood of being used properly and resulting in clean shutdown of threads and apps in general. Why isn't it?
Interruption is supposed to be cooperative. I think the designers wanted to avoid a situation where you could blow away a thread by interrupting it, where the thread didn't have code to handle that eventuality. The intention seems to have been to make the Runnable code explicitly decide how to handle interruption. A lot of framework or language code seems to be about deciding whose responsibility something should be, and trying to make the correct usage apparent, in order to minimize how badly users get burned. This is one of those judgment calls.
With InterruptedException being checked, the worst case is that the exception is caught, but in a way that isn't awfully useful. (Actually the absolute worst case is the interrupt flag is not restored, leaving any following code in the thread unaware that the interruption happened.) If InterruptedException was unchecked (or if you wrap it in a RuntimeException, as shown in the article linked in the comments), the exception could go unhandled and proceed to terminate the thread, which could be really bad if the thread was not at a stopping place.
Toy examples and simple code would work better with unchecked InterruptedExceptions; nobody would bother with catching the exception and it would just work. However, in real code doing substantial work this was probably considered detrimental.
Making the exception checked is an attempt to ensure that the developer knows the exception can be thrown so that the developer can avoid the situation where the exception gets thrown in the middle of work the thread is doing, potentially leaving the work partially-done in a bad state.
I am writing a fairly large, multithreaded application, with many differing roles for threads (e.g. event processing, metrics, networking). Currently, if there is any inconsistency that cannot be handled, it will manifest itself as an exception. Since there's really no way to recover from some of them, I've been rethrowing it as a runtime exception of type ApplicationDeathException.
Any classes that need to handle shutdown would call it from a catch block for this exception, and then rethrow it in order for it to propagate up the stack).
I am considering killing off all other threads in this same manner by calling Thread#stop(Throwable) upon them. Most are fine with sudden termination, and can catch this exception should there be a need for shutdown logic. They will simply have the exception propagate up the stack, performing shutdown logic whereever needed, and eventually just killing the thread in the end. Are there any hidden dangers that I'm missing with this approach?
Thread.stop has been deprecated since it is unsafe (see the Javadoc). Instead have each thread monitor a boolean flag of some sort (see Java: How to stop thread? and likely countless other threads on SO).
In situations like this I typically implement some sort of thread pool manager that is responsible for cleanly shutting down running threads. Then when something really bad happens you only need to notify the manager to shut things down.
I am writing a game program, and rarely i will get an exception. I want to be able to record all the exceptions i get on a separate thread. My program is already multi-threaded. In some cases i use try catch, and for those i could just set an exception variable to the caught exception. However i want to be able to find out all exceptions that have been thrown on all threads without putting every statement in a try catch. For clarification i want the exception object not just the name of the exception.
You want the Thread.UncaughtExceptionHandler:
Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.
See here for details.
This can be done using Spring AOP which is useful in these cases.
#AfterThrowing aspect
You will require Spring AOP libraries for that.
A similar question was answered previously.
This can be done through Java Debug Interface (JDI) that is part of Java Platform Debugger Architecture (JPDA).
In particular, see ExceptionRequest and ExceptionEvent.
Is there a way to make my java application shut down there is an error? e.g. if I have a nullpointerexception, can I just make it completely close out?
Any uncaught exception at the top level will automatically halt the thread it's in. If you have more than one thread in your program, the other threads will still survive. If you want to terminate explicitly, you can call System.exit()
You can use System.exit(0); to terminate the JVM.
However, you should avoid NullPointerException by checking the reference before using it:
if(foo != null) foo.doSomething();
As others have said, catching the exception and calling System.exit() is (generally) the right approach. But there is more to it than that:
Q: Do I really need to catch it?
A: If your application is a conventional command-line application, and the exception is thrown on the "main" thread, then you may not need to catch it. Uncaught exceptions on the main thread will cause the application to exit ... if there are no other non-daemon threads in existence. (In fact, the same thing goes for any thread ... )
However if your thread has more than one non-daemon thread, then you need to do something to stop the application. Like catch the exception and call exit().
Q: Where do you catch it?
A: On the stack of any thread where the "fatal" exception might be thrown. There are two ways to do this:
Put a try / catch (Throwable) in the main(String[]) method, a thread's run() method, etcetera.
Install a default uncaught exception handler.
What you DON'T want to do is to add System.exit() calls all through your codebase. That approach leads to all sorts of problems with reusability, unit testing and generally figuring out "why has the effing application died again".
Q: What if it is already caught?
A: One reason why your application might not be exiting naturally, is that your code is already catching the exception ... by accident. For instance:
try {
doSomething()
} catch (Exception ex) {
handle an IO exception
}
In the above, some ignorant / lazy programmer hasn't bothered to consider the exceptions that might be thrown in doSomething and has assumed that they are all some kind of IO related exception. But if the exception was actually an unexpected NullPointerException ... or something worse ... then the code has just squashed it.
The cure for this kind of thing is code-reviews and mentoring to cure the programmer of his bad habits ... hopefully before he does too much damage to the codebase! And if you find this kind of thing in your codebase, you should fix it immediately ... and probably "grep" for similar occurrences and fix them too.
I'm relatively new to Threading in Java and I've noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.
What kind of behaviour causes this, and in simple applications where I have a monitor thread can I just Ignore the exception?
It happens when something calls interrupt() on the thread. This article by Brian Goetz explains the interruption mechanism and how you should handle InterruptedExceptions:
"The most common response to InterruptedException is to swallow it -- catch it and do nothing (or perhaps log it, which isn't any better) -- as we'll see later in Listing 4. Unfortunately, this approach throws away important information about the fact that an interrupt occurred, which could compromise the application's ability to cancel activities or shut down in a timely manner."
"If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred [...]. This task is accomplished by calling interrupt() to "reinterrupt" the current thread."
As others have said, it is caused by some other thread calling interrupt() on the Thread object that is sleeping.
What this means in plain english, is that some other thread has decided to cancel the sleeping thread. The try/catch block is there so you can gracefully handle the cancellation of the thread, and safely clean up any resources, or shut down whatever operation it was doing correctly.
If you don't actually need to do any of that, then yes, you still need an empty catch block. But that's Java for you...
Some advices from Java Concurrency in Practice:
Propagate the exception (possibly after some task-specific cleanup), making your method an interruptible blocking method, too; or
Restore the interruption status so that code higher up on the call stack can deal with it.
Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.
The primary case is when someone calls Thread.interrupt() on your thread.
It may be safer to throw a RuntimeException if it happens when you're really not expecting it, but for very simple cases you can probably ignore it.
From the javadocs:
Class InterruptedException
Thrown when a thread is waiting,
sleeping, or otherwise paused for a
long time and another thread
interrupts it using the interrupt
method in class Thread.
Hope that answers your question.
Well if some other Thread calls thread.interupt(), while the thread is sleeping, you'll get the Exception. And yes, you can probably just put try..catch arround the sleep() and ignore it ;)
InterruptedException is a checked exception so unfortunately you cannot just ignore it. In most simple cases you do not have to do anything in the catch clause because you are sure that it will not happen.
From the API
Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.