public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 2345);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Map<Integer, Integer> testMap = new HashMap<Integer, Integer>();
testMap.put(1,1);
oos.writeObject(testMap);
oos.flush();
testMap.put(2,2);
oos.writeObject(testMap);
oos.flush();
oos.close();
}
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(2345);
Socket s = ss.accept();
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println((HashMap<Integer, Integer>) ois.readObject());
System.out.println((HashMap<Integer, Integer>) ois.readObject());
ois.close;
}
The code above is from two files.
When running them, the console prints the same result:
{1=1}
{1=1}
How can this happen?
An ObjectOutputStream remembers the objects it has written already and on repeated writes will only output a pointer (and not the contents again). This preserves object identity and is necessary for cyclic graphs.
So what your stream contains is basically:
You need to use a fresh HashMap instance in your case.