Java Reference
In-Depth Information
name = copy.name;
team = copy.team;
pos = copy.pos;
} catch (IOException e) {
System.out.println(
"unable to open file for player, creating new player object");
name = "unknown";
} catch (ClassNotFoundException e) {
System.out.println("unable to read file for player");
}
}
protected void writeState() {
try {
ObjectOutputStream writeOut =
new ObjectOutputStream(new FileOutputStream(
filePrefix + id.toString()));
writeOut.writeObject(this);
writeOut.close();
changed = false;
} catch (Exception e) {
System.out.println("unable to write object");
e.printStackTrace();
}
}
protected void finalize(){
if (changed){
writeState();
System.out.println("writing state in finalizer");
}
}
...
}
Our constructor that reads in a Player state from the filesystem now closes the ObjectIn-
putStream immediately after the read. We now have a writeState() method that will write
any changed state to the filesystem and update the changed flag to show that the state in the
filesystem is the same as the state in the program. We still have a finalizer, but all it does is
a last-gasp check on the changed flag. If, somehow, a mistake has been made in the program
and some alteration of the Player state has been made without a call to writeState() , the
finalizer will make the call to update the permanent record. This is the coding equivalent of
wearing both a belt and suspenders, and is evidence of a level of paranoia that is common
Search WWH ::




Custom Search