How to deserialize synchronizedMap and synchronizedList?
This is probably just a question of syntax (and my inability to find it ;)
Here's the collections to be (de)serialized:
private Map<String, Terminal> terminals = Collections.synchronizedMap(new HashMap<String, Terminal>());
private List<Host> hosts = Collections.synchronizedList(new ArrayList<Host>());
Here goes serialization:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("blah.dmp"));
out.writeObject(synchronizedMap);
out.writeObject(synchronizedList);
and now de-serializing, this throws a ClassCastException (obviously):
terminals = (HashMap<String, Terminal>) in.readObject();
hosts = (ArrayList<Hosts>) in.readObject();
开发者_如何学运维
but the following won't compile (as well as manyyyyy other variations i've tried):
terminals = (Collections.synchronizedMap(new HashMap<String, Terminal>())) in.readObject();
hosts = (Collections.synchronizedList(new ArrayList<Host>())) in.readObject();
What about this?
terminals = (Map<String, Terminal>) in.readObject();
hosts = (List<Hosts>) in.readObject();
A Map
or List
wrapped by Collections.synchronizedMap
/ Collections.synchronizedList
should be deserialized just fine without needing to re-wrap it.
This syntax should "work", but with a valid warning:
terminals = (Map<String, Terminal>) in.readObject();
To eliminate the warning and ensure 100% type safety, you'd need to iterate over the contents of the map, and check their type:
Map<?, ?> tmp = (Map<?, ?>) in.readObject();
Map<String, Terminal> copy = new HashMap<String, Terminal>();
for (Map.Entry<?, ?> e : tmp.entrySet())
copy.put((String) e.getKey(), (Terminal) e.getValue());
terminals = Collections.synchronizedMap(copy);
精彩评论