【发布时间】:2017-01-01 16:05:56
【问题描述】:
为了从特定的序列化格式中抽象出来,我想定义以下内容:
public interface TransportCodec {
void write(OutputStream out, Object obj) throws IOException;
Object read(InputStream in) throws IOException;
}
默认实现会像这样使用 Java 对象序列化:
public void write(OutputStream out, Object obj) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(obj);
oout.flush();
}
显然oout.close() 丢失了,但有一个原因:我希望能够通过独立调用write 将多个对象写入同一个流。查看ObjectOutputStream(jdk 1.8)的源代码,oout.close() 关闭了底层流,但也清除了属于ObjectOutputStream 的数据结构。但是由于我将oout 留给了垃圾收集器,所以我不会期望不关闭流会出现问题。
除了未来的 JDK 确实需要oout.close() 的风险之外,还有两个问题:
- 如果不关闭上面的
ObjectOutputStream,我在当前的 JDK 中会丢失什么。 - 首先序列化为
ByteArrayOutputStream,然后将字节复制到out将允许关闭oout。有更好的选择吗?
【问题讨论】:
标签: java serialization objectoutputstream