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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With