Basically, I have a class with 2 methods: one to serialize an object into an XML file and another to read an object from XML. Here is an example of synchronized part from the method that restores an object:
public T restore(String from) throws Exception {
// variables declaration
synchronized (from) {
try {
decoder = new XMLDecoder(new BufferedInputStream(
new FileInputStream(from)));
restoredItem = decoder.readObject();
decoder.close();
} catch (Exception e) {
logger.warning("file not found or smth: " + from);
throw new Exception(e);
}
}
// try to cast it
}
A similar approach is taken when serializing an object. Now, when I create a unit test which in turn creates 10 threads with each thread trying to serialize and instantly read either a Boolean or a String it would fail showing that ClassCastExceptions occur. This makes me think that I get serialization wrong (everything's ok in a single-threaded environment). If you've stayed with me down to this point :), here are the 2 issues I need your help on:
- does it make sense to synchronize on a string argument passed to method (considering there's a string pool in java)? BTW, I've tried synchronizing on the XMLSerializer class itself with result staying the same.
- how do i correctly synchronize io operations on a single file?