问题描述
据我了解,Java的Exception类当然不是一成不变的(诸如 initCause
和 setStackTrace
之类的方法提供了一些线索那)。那么至少它是线程安全的吗?假设我的一个班级有一个这样的字段:
As I understand, Java's Exception class is certainly not immutable (methods like initCause
and setStackTrace
give some clues about that). So is it at least thread-safe? Suppose one of my classes has a field like this:
private final Exception myException;
我可以安全地将此字段公开给多个线程吗?
我不愿意讨论发生这种情况的可能性和原因。我的问题更多是关于该原理的:我可以说一个暴露Exception类型的字段的类是线程安全的吗?
Can I safely expose this field to multiple threads?I'm not willing to discuss concrete cases where and why this situation could occur. My question is more about the principle: can I tell that a class which exposes field of Exception type is thread-safe?
另一个例子:
class CustomException extends Exception
{
...
}
此类是线程安全的吗?
推荐答案
注意 initCause()
是同步的
和 setStackTrace()
的副本
所以 Exception
实际上似乎是在线程安全中实现的心神。不过,对于任何在线程之间例行传递异常的设计(例如,除了处理非常严重的错误情况以外的任何其他原因),我都会保持警惕。只是感觉不对。
So Exception
actually does seem to be implemented with thread-safety in mind. Still, I'd be wary of any design where exceptions are routinely passed around between threads (i.e. for any reason other than handling a very serious error condition). It just feels wrong.
这篇关于Java:Exception类是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!