作者AmosYang (Zzz...)
看板java
标题Re: [问题] Tomcat杂问
时间Sun May 6 15:14:56 2012
※ 引述《LaPass (LaPass)》之铭言:
: → LaPass:现在我看到Serializable就头大.... 这东西不好用....orz 05/05 15:15
: → LaPass:4板... 有点久不过我先去找来看看 05/05 15:27
: 推 PsMonkey:敢问 Serializable 哪里不好用? 05/06 01:04
: 看到libary中有 Serializable 这个东西
: 通常就是准备一个物件存成档案、透过网路线传到别的地方去之类的
: 大部分的状况下,用起来还不错
: 但是我在传的时候常常遇到一种问题
[deleted]
: 虽然我没看到解释这种状况的文
: 但是我猜Serializable在传递Object时,会先检查参照
: 如果有跟曾经传过的物件的参照一样,就直接使用上一次传过去的值
: 所以,在用Serializable的时候,不小心的话会出现难以发现的bug
这现像在 2000 年的这文章里有提到,以下节录可供参考的部分 (整篇文章也值得一读)
http://java.sun.com/developer/technicalArticles/Programming/serialization/
Caching Objects in the Stream
First, consider the situation in which an object is written to a stream and
then written again later.
By default, an ObjectOutputStream will maintain
a reference to an object written to it. That means that if the state of the
written object is written and then written again, the new state will not be
saved! Here is a code snippet that shows that problem in action:
10 ObjectOutputStream out = new ObjectOutputStream(...);
20 MyObject obj = new MyObject(); // must be Serializable
30 obj.setState(100);
40 out.writeObject(obj); // saves object with state = 100
50 obj.setState(200);
60 out.writeObject(obj); // does not save new object state
There are two ways to control that situation.
First, you could make sure
to always close the stream after a write call, ensuring the new object
is written out each time. Second, you could call the
ObjectOutputStream.reset() method, which would tell the stream to
release the cache of references it is holding so all new write calls
will actually be written. Be careful, though -- the reset flushes the
entire object cache, so all objects that have been written could be
rewritten.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 98.26.14.35
1F:→ LaPass:谢谢,当初找资料时也看过reset这个东西 05/06 15:41
2F:推 lovdkkkk:reset 勤一点也比较不容易 OutOfMemory 05/06 17:11