简体   繁体   中英

Is catching Throwable in schedulers a good practice?

I rather say that fail fast and not catching Throwable is a good practice. But in case unhandled exception in request processor like StackOverflowError, the task may be stopped. And that doesn't always sound good. I'd rather catch StackOverflowError over and over, but some tasks might be processed. What is good practice here?

There is no "good practice" or "best practice" 1 about catching Error and hence Throwable .

  • On the one hand, a JVM can recover successfully from some kinds of Error in some circumstances. For example, if you are running "task" on a single thread that doesn't interact with other threads (directly or indirectly), then that thread can safely recover from a StackOverflowError and possibly 2 a OutOfMemoryError .

  • On the other hand, many Error subclasses indicate that the application or JVM is in a state where recovery is not possible, or not practical:

    • A class loading or initialization Error means that certain classes will be an unusable state. An application that depends the class won't be able to proceed.
    • If an application that uses notify / wait or higher level synchronization constructs gets (say) an OutOfMemoryError error on one thread, it is liable to leave other threads waiting for notifications, etc that may never arrive.

My recommendation would be to heed the implied advice in the javadoc for Error and not to catch and attempt recover from Error or its subclasses. If you attempt to recover, allow for the possibility that the application may "wedge".


1 - Actually, there is not "best practice" at all; see https://www.satisfice.com/blog/archives/5164

2 - This depends on the root cause. If the root cause is a memory leak elsewhere in your codebase, then recovery is a bad idea. The OOME is likely to recur ... with increasing frequency.

This is from the javadoc of Error :

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

I usually follow this rule to avoid suppressing real unexpected errors that should be fixed.
You mentionned StackoverflowError , if you have this kind of error, there's probably a problem with your algorithm and your code should be optimized.

If you know that a specific error is likely to be thrown and you're okay with that, you can catch it. However if you don't expect it, it's better to raise the alarm ASAP and deal with it.

Good practice is catch scheduled jobs, write log about exception, metrics and(optional) reschedule it.

Also, sometimes your thread will be stoped/destroyed (hello spring schedulers) cause you receive some sort of exception, that not critical to your job...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM