Java – is it safe to share exception instances
We are making a system similar to excel When we open the document and find an unsupported function, we throw an exception We only support a subset of Excel functions, which may occur frequently The problem is that when many cells contain unsupported functions, a large number of exception instances will be created Creating many of these exception instances takes time that cannot be ignored
We don't have any special properties in the exception class What we need to know is the fact that exceptions are thrown We just found that an error has occurred and marked the cell as an error
So we decided to share an exception instance and throw it when needed Multiple threads can throw exception instances I suspect that the stack trace may be corrupted, but we don't see it We just catch exceptions and mark the corresponding cells as errors
My question is: is it safe to share exception instances in this case? Well, I read the following article: Java: is exception class thread safe? But the background seems different
Thank you for reading this long question and reply in advance
Solution
Yes, if you are careful
If you are not careful, for example, getstacktrace may screw up Make sure each thread has its own exception object, or override getstacktrace and return an empty array
(in some cases, the JVM will actually reuse the exception instance. If the memory is insufficient, it will reuse the pre allocated outofmemoryerror instead of trying to create a new one. In this case, getstacktrace returns an empty array.)
Related questions:
> How can a preallocated OutOfMemoryError truthfully implement Throwable. getStackTrace if thrown twice?