共享异常实例是安全的 [英] Is it safe to share exception instance

查看:139
本文介绍了共享异常实例是安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在制作一个类似Excel的系统。当我们打开文档并发现不支持的功能时,我们抛出异常。我们只是支持小部分的excel函数,这可能会频繁发生。问题是当有很多单元格包含不受支持的函数时,会创建很多异常实例。并且创建这些许多异常事件消耗了无限量的时间。



我们在异常类中没有任何特殊的属性。我们需要知道的是抛出异常的事实。我们只是发现错误已经发生,并将该单元格标记为错误。



所以我们决定共享一个异常实例,并在需要时抛出它。异常实例可以被多个线程抛出。我怀疑堆栈跟踪可能被破坏,但是我们看不到它。我们只是捕获异常,并将相应的单元格标记为错误。



我的问题是:
在这种情况下,是否可以共享异常实例?

嗯,我阅读了以下文章:
Java:是Exception类线程安全?
但是上下文似乎是不同的。



感谢您阅读这个长期的问题,

解决方案


[...]是安全的分享异常实例?


是的,如果你小心。
$ b

如果您不小心, getStackTrace 可能会搞砸了。确保每个线程都有它自己的异常对象,或覆盖 getStackTrace 并返回一个空数组。



在某些情况下,JVM实际上重用异常实例,如果内存不足,它将重新使用预先分配的 OutOfMemoryError 而不是尝试创建一个新的例子,在这种情况下 getStackTrace 返回一个空数组。)



相关问题:




We are making an Excel-like system. When we open a document and found unsupported functions we threw exception. We just support small subset of excel functions, this could happen frequently. The problem is when there are a lot of cells that contains unsupported functions, lots and lots of exception instances are created. And creating those many exception instances consumes unignorable amount of time.

We don't have any special properties within the exception class. What we need to know is the fact that the exception is thrown. We just found that the error has occurred and mark the cell as error.

So we decided to share one exception instance and throw it whenever needed. The exception instance can be thrown by multiple threads. I suspect that the stack trace could be corrupted, however, we don't see it. We just catch the exception, and mark the corresponding cell as error.

My question is: In this situation, is it safe to share exception instance? Well, I read the following article: Java: is Exception class thread-safe? But the context seems to be different.

Thank you for reading this long question and response in advance.

解决方案

[...] is it safe to share exception instance?

Yes, if you're careful.

If you're not careful, the getStackTrace for instance may get messed up. Either make sure each thread has it's own exception object, or override getStackTrace and return an empty array.

(The JVM actually reuses exception instances in some cases. If it runs out of memory, it will reuse a preallocated OutOfMemoryError instead of trying to create a new one for instance. In this case the getStackTrace returns an empty array.)

Related question:

这篇关于共享异常实例是安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆