Serializable类持有Thread引用正常,初始化为何抛出NotSerializableException?
关于Serializable类与Thread引用序列化的问题解答
Let’s break down your two questions clearly, since they touch on a common gotcha with Java’s serialization mechanism:
1. 为何在Serializable类中持有Thread引用是可行的,但初始化该引用会抛出NotSerializableException?
The key here lies in how Java handles null references during serialization:
- When you declare a
Threadfield in aSerializableclass but leave it asnull(the default for reference types), the serialization process simply skips this field—there’s no actual object to serialize, so it doesn’t check if the type is serializable. That’s why just holding the reference (without assigning a real Thread instance) works fine. - Once you initialize the reference to a concrete
Threadobject, the serialization mechanism tries to serialize that Thread instance. SinceThreaddoes not implement theSerializableinterface, this triggers aNotSerializableExceptionimmediately.
2. 原有代码可正常运行,但取消注释a.setTh(new Thread());语句时会抛出该异常,既然Thread不实现Serializable接口,为何默认序列化过程此前未对"th"变量报错?
Again, this boils down to the default value of reference types in Java:
- By default, your
thfield is initialized tonull. The Java serialization engine doesn’t perform any checks on null fields—there’s nothing to serialize, so it doesn’t validate whether the field’s type is serializable. - When you uncomment
a.setTh(new Thread());, you’re assigning a non-nullThreadinstance to the field. Now, during serialization, the engine attempts to write thisThreadobject to the stream. SinceThreadisn’t serializable, it throws the exception you’re seeing.
如何避免这个异常?
If you need to keep the Thread field in your serializable class but don’t want to serialize it, mark the field as transient:
private transient Thread th;
This tells the serialization process to skip the field entirely, regardless of whether it’s null or holds a valid Thread instance.
内容的提问来源于stack exchange,提问作者shrishti
相关产品推荐
相关产品推荐

