通过 ObjectOutputStream 发送相同但已修改的对象
我的以下代码显示了我的错误或误解。
我发送了相同的列表,但通过 ObjectOutputStream 进行了修改。 一次为[0],其他为[1]。 但当我读它时,我得到了两次[0]。 我认为这是由于我发送同一个对象而 ObjectOutputStream 必须以某种方式缓存它们造成的。
这是应该的工作,还是我应该提交一个错误?
import java.io.*;
import java.net.*;
import java.util.*;
public class OOS {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
ServerSocket ss = new ServerSocket(12344);
Socket s= ss.accept();
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
List<Integer> same = new ArrayList<Integer>();
same.add(0);
oos.writeObject(same);
same.clear();
same.add(1);
oos.writeObject(same);
} catch(Exception e) {
e.printStackTrace();
}
}
});
t1.start();
Socket s = new Socket("localhost", 12344);
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
// outputs [0] as expected
System.out.println(ois.readObject());
// outputs [0], but expected [1]
System.out.println(ois.readObject());
System.exit(0);
}
}
I have the following code that shows either a bug or a misunderstanding on my part.
I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.
Is this work as it should, or should I file a bug?
import java.io.*;
import java.net.*;
import java.util.*;
public class OOS {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
ServerSocket ss = new ServerSocket(12344);
Socket s= ss.accept();
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
List<Integer> same = new ArrayList<Integer>();
same.add(0);
oos.writeObject(same);
same.clear();
same.add(1);
oos.writeObject(same);
} catch(Exception e) {
e.printStackTrace();
}
}
});
t1.start();
Socket s = new Socket("localhost", 12344);
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
// outputs [0] as expected
System.out.println(ois.readObject());
// outputs [0], but expected [1]
System.out.println(ois.readObject());
System.exit(0);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
流有一个引用图,因此发送两次的对象不会在另一端给出两个对象,您只会得到一个。 分别发送相同的对象两次将为您提供相同的实例两次(每个实例都具有相同的数据 - 这就是您所看到的)。
如果你想重置图表,请参阅reset()方法。
The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).
See the reset() method if you want to reset the graph.
最大是正确的,但您也可以使用:
请参阅下面的评论以了解警告
Max is correct, but you can also use:
See comment below for caveat