单身例外工作吗? [英] Do singleton exceptions work?

查看:166
本文介绍了单身例外工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在工作中的一个同事介绍了静态工厂方法(从Java开始),然后给出了一个用于获取静态/单例异常的例子。



这为我设置了一个红旗。不是例外状态吗?堆栈跟踪信息不是由JVM填充的吗?你真正得到了什么节省,因为例外应该只发生在特殊情况下?



我对于例外的了解是非常有限的,所以我来找你这将是单例异常工作,是否有任何理由使用它们?

解决方案

单例异常应该是性能优化。想法是,当创建异常通常是异常最昂贵的部分时,您消除了填充堆栈跟踪的费用。



如果异常足够独特和描述性并且堆栈跟踪不会被使用,那么单例可能有效。您可以设计应用程序,使得具有特定消息的特定异常类型总是意味着从特定位置进行异常处理。那么堆栈跟踪将是无关紧要的。



2003年4月22日Tech Tips文章描述了您重复使用异常的场景。在这种情况下,他们试图通过减少创建的对象数量来游戏垃圾收集器。如果您跳过 populateStackTrace()调用,则不用担心线程。



一般来说,如果异常的性能影响是导致问题,这是一个迹象表明异常正在用于应用程序逻辑,应该使用错误代码。



在较新的JVM( 1.4+,我相信),这个优化可以由JVM在-server模式下运行时自动完成。这个热点优化可以通过选项 -XX:+ OmitStackTraceInFastThrow 来控制。



我个人认为建议不要使用单例异常[anti]模式。


A collegue of mine at work gave a presentation on static factory methods (right out of Effective Java), and then gave an example of its use for obtaining static / singleton exceptions.

This set off a red flag for me. Aren't exceptions stateful? Aren't they populated by the JVM for stack trace info? What savings do you really get with this, since exceptions should only occur for, well, exceptional situations?

My knowledge on Exceptions is rather limited, so I come to you with this: will singleton exceptions work, and is there any reason to use them?

解决方案

Singleton exceptions are supposed to be a performance optimization. The thinking is that you eliminate the cost of populating the stack trace when creating an exception which is usually the most expensive part of exceptions.

If the exception were sufficiently unique and descriptive and the stacktrace was not going to be used, then a singleton could potentially be effective. You could design the app such that a specific exception type with a specific message always means that an exception orgininated from a specific location. Then the stack trace would be irrelevant.

The April 22, 2003 Tech Tips article describes a scenario where you reuse an exception. In this case, they are trying to game the garbage collector by reducing the number of objects created. If you skipped the populateStackTrace() call, you would not have to worry about threading.

Generally, if the performance impact of an exception is causing problems, that is a sign that exceptions are being used for application logic and an error-code should be used instead.

In newer JVM's (1.4+, I believe), this "optimization" can be done automatically by the JVM when running in "-server" mode. This hotspot optimization can be controlled by the option -XX:+OmitStackTraceInFastThrow.

Personally, I would recommend against using the singleton exception [anti-]pattern.

这篇关于单身例外工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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