views:

79

answers:

2

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();
+3  A: 

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.

ZoogieZork
Haha boy do i feel dumb now ;) What i find particularly odd though, is if i change my synchronizedMap initialization to a regular HashMap, my case which causes a ClassCastException works fine.
glenneroo
+1  A: 

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);
erickson
You are awesome! Your addendum just answered the other question i was about to post! ;)
glenneroo