Java uncaught global exception handler for ALL threads - java

I asked a question about how to override the default Java Exception handling here and was told the answer here.
The question is now : is there a way to generify this handler to all threads without declaring explicitly in each thread ?
I think it should be possible to get all threads in some way, then bind them the exception handler ?

Use Thread.setDefaultUncaughtExceptionHandler. As the javadoc says:
"By setting the default uncaught exception handler, an application can change the way in which uncaught exceptions are handled (such as logging to a specific device, or file) for those threads that would already accept whatever "default" behavior the system provided."
Obviously, if a Thread already has a (non-default) handler, then it won't be affected by a change to the default behavior.
I think it should be possible to get all threads in some way, then bind them the exception handler ?
That's not necessary ... unless you want to change a thread's non-default handler. If you really need to do that, you can find all threads by traversing the application's ThreadGroup hierarchy. (Unless your app is sandboxed ...)
Edit
The thread list of the running app can be found using this answer :
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

You can use Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) for that case if i got it right.
See Thread.setDefaultUncaughtExceptionHandler

There is a method setDefaultUncaughtExceptionHandler in Thread

Related

How to check if a Java thread terminated with exception?

Given a thread that has finished doing some work (its status is Thread.State.TERMINATED), is there a way to understand if the thread has completed the Thread.run()/Runnable.run() method correctly or has thrown an uncaught throwable ?
Afaik, a thread goes into the TERMINATED state both when exiting normally and when throwing throwables.
Somebody suggested using an UncaughtExceptionHandler. Given that a thread can have only one UncaughtExceptionHandler (other than the default for all threads), and that the thread code can change the provided one, is it a good practice using them ?
Have you looked at Thread.setUncaughtExceptionHandler?
This lets you trap uncaufht exceptions if you have a handle on the thread?
You could install an UncaughtExceptionHandler or set the default UncaughtExceptionHandler and have it save the exception that the thread exited with.
The functionality you are interested in could be accomplished using a Callable that wraps it run method in a try { } catch block and returns the Exception within the Future object it it encountered a problem
I don't know if there is a way to directly do it, but you could surround all your code in the run method with a try/catch statement. If you create a boolean and set it to true when it terminates with a exception then you can you can check the state and if the boolean is true it terminated with an exception and if the boolean is false then it closed correctly.
There is probably a better way but this should work.

Setting custom RejectedExecutionHandler for ThreadPoolExecutor after executing some tasks?

I am using Java ThreadPoolExecutor in one of my Android components. My question is that :
Is it a good practice to set RejectedExecutionHandler using setRejectedExecutionHandler() after executing some tasks to the TPE ?
I mean are there any side effects of doing this. Is it a good practice?
Edited
I am required to create a ThreadPoolManagementLibrary project in Android which can be used by other projects. Now, I need to expose public methods of TPE in my component. If I let the user set RejectedExecutionHandler then would it be a problem?
The question should be "Should we handle the RejectedExecutionException?". The answer is of course yes. Not doing so will crash the thread in which it occurs i.e. the thread submitting the task for execution, and the application will continue running in an unknown state.
The second question is "What should we do to handle this exception?". We should probably stop the application as cleanly as possible. As this is true also for other runtime exceptions (and errors, by the way), one solution is to use an UncaughtExceptionHandler. But if we want to handle the RejectedExecutionException in a specific manner, we may use a RejectedExecutionHandler. This could be used to do some specific handling before stopping the application (either directly or by throwing a new RuntimeException that will be caught by the UncaughtExceptionHandler).
The main point here is that all exceptions and errors should be handled. This is against so call "best practices", but these practices are just wrong. They were right once for single thread applications. The world has changed. A runtime exception or an error will crash the thread in which it occurs, not the application. So it MUST BE HANDLED.
Of course, if you are using a framework or an application server, the problem may be different because this server or framework will probably handle the uncaught exceptions for you.
I don't think so. Let us try to understand what a RejectedExecutionHandler does?
When you submit submit a task to the ThreadPoolExecutor then following sequence of event happens:
If there is any worker thread free which is free and can run this task.
Else it will try to move this task to the workerqueue from where a worker thread will pick up the task if it is free.
If the workerQueue is also full then it will try to create a new thread if possible(no of worker threads are less than maxPoolSize).
If all the above fails then the task is sent to the handler and the default handler throws a RejectedExecutionException.
So basically, if you allow user to set their own handler then you are giving them freedom to handle the rejected task in their own way. They should be careful while implementing it.
I would also agree with #user2120553 .
All the points #Braj Kishore mentioned are correct, but I would like to mention that if we declare our custom RejectedExecutionHandler then we would surely get a chance to retry the execution.

Tracking all exceptions in program

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.

Who interrupts my thread?

I understand what an InterruptedException does and why it is thrown. However in my application I get it when waiting for SwingUtilities.invokeAndWait() on a thread that is only known by my application, and my application never calls Thread.interrupt() on any thread, also it never passes the reference of the thread on to anyone.
So my question is: Who interrupts my thread?
Is there any way to tell? Is there a reason why the InterruptedException doesn't contain the name of the Thread that requests the interrupt?
I read that it could be a framework or library that does this, we use the following, but I can't think of reason for them to interrupt my thread:
Hibernate
Spring
Log4J
Mysql connector
If possible, you could extend Thread and overwrite the interrupt() method for this thread to print a stacktrace or throw an unsupported operation exception.
You could also use the extended Thread class to store a reference to the interrupting thread and read it once you catch the interrupted exception.
In general, if you want to know who is doing something, attach a debugger, put a breakpoint, and there you go. No need for guessing if you can reproduce it!
In this case, you can put a breakpoint at Thread.interrupt(). If there are other threads that are being interrupted too (so you have "false positive" hits on the breakpoint), you could add a breakpoint condition (most IDE's allow you to do that easily), for example by checking the name of the thread.
There is something strange here.
From the javadoc of invokeAndWait, an InterruptedException is thrown
if we're interrupted while waiting for the event dispatching thread to finish excecuting doRun.run()
Have you tried to see if the code executed in the EDT sends any exception ? Or do the code in that EDT tries to modify some of this thread's variables (I know this term is not "orthodox" in java language, but I hope you see what I mean : any code implying synchronized, wait, join, ...

Calling a method on thread termination

I am writing a java program which tracks as threads are created in a program and is then supposed to perform some work as each Thread terminates.
I dont see any 'thread termination hooks' out there in the javadoc.
Currently the only way I can think of to achieve my requirement is to hold on to the thread objects and query its 'state' at repeated intervals.
Is there any better way to do this?
Edit:
I cannot wrap the runnable or modify the runnable in any way.
My code uses runtime instrumentation and just detects that a thread is created and gets a reference to the Thread object.
The runnable is already running at this point.
You can use the join() method.
EDIT
If your main thread must not be blocked until threads are not terminated, you can create a sub main thread which will call the threads, then wait for them with join() method.
I see four possible methods.
Use your own Thread subclass with an
overridden run() method. Add a
finally block for thread
termination.
Use a Runnable with
similar decoration, perhaps as a
wrapper around the supplied
Runnable. A variant of this is to
subclass Thread in order to apply
this wrapper at construction time.
Create a 2nd thread to join() on the
real thread and thus detect its
termination.
Use instrumentation to rewrite the Thread.run() method as above.
Just poking around in the (sun 1.5) source code for java.lang.Thread and sun.misc.VM, there is a field in thread called threadStatus. It is a private int and its values map to the enum java.lang.Thread.State. I have not verified this, nor determined how quickly it occurs if it does, but when a thread eventually terminates, this value will be set to java.lang.Thread.State.TERMINATED.
With this relatively simple condition to detect, I think it would be fairly straightforward to inject a field interceptor on threadStatus to fire an event when the field is set to a specific target value.
You could write a decorator for Runnable which calls a termination hook and wrap your thread code in it when you create the threads.
If you added a try/finally block to each run method, the code inside would be executed when each thread completed. Let the thread be responsible for its own clean-up.
AspectJ could help you do this if you needed to inject code into third-party compiled code, but apparently it doesn't work on standard Java class libraries.
Looks like there's a whitepaper on doing this here, but there's no telling if it's practical. I think you have to pay for it.
http://portal.acm.org/citation.cfm?doid=1411732.1411754
You could download OpenJDK, put the hook in yourself, compile a custom JRE and ship that with your application :)
As you say, there are no thread termination hooks. You have to code them yourself; call some method on a controller at the end of the run() method of your Runnables (AFAIK subclassing Thread is considered bad practice, you should implement Runnable and create a Thread with that Runnable as its target).
You can also implement an UncaughtExceptionHandler to know if a thread terminated abnormally due to an exception, in which case your controller's method won't be called.
If you run on java 1.5 you can probably do it using java.lang.instrument and the -javaagent option to the jvm.
Redefine the run method on the thread object which should call your code. You already seem to use instrumentation so it should be available. as it modifies runtime bytecode you should be fine
That said, it is hard to provide a more specific and detailed answer your question lacks at least the jvm version and the main frameworks in use (think spring-aop, jboss-aop, jvm version etc)

Categories

Resources