javamultithreadingjvmstack-overflow

Is it safe to catch stack overflows? Can it leave objects in messy/intermediate states?


I've been reviewing ways to kill threads in Java, and the overwhelming conclusion is that it is never safe to stop code at arbitrary points - doing so may leave resources in messy intermediate states. This is why Thread.stop() was deprecated forever and eventually removed in favor of cooperative thread management.

However, it occurs to me that this is exactly what a stack overflow does - it may be thrown from (as I understand it) any line of java code that tries to reach for more stack space than is available. If you catch a stack overflow exception from an arbitrary thread (in my use case, semi-trusted user code), can that mean runtime objects are left in illegal states? (Un-released locks, open connections, "atomic" operations stopped halfway thru?)


Solution

  • A stack overflow in Java is a StackOverflowError, not a StackOverflowException.

    The documentation of Error specifies

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

    As you have correctly observed, a StackOverflowError may occur at any point in a program and may leave objects in arbitrarily broken states. You cannot reasonably recover from a StackOverflowError.

    Do not try.