Everyone knows its ideal to do all disk io (loading/saving character files, chat logs, etc.) on a separate thread. Writing is obviously easily done but what about reading? If you wanted to do reading wouldn't you have to use a Phaser or some other sort of blocking object (CountDownLatch would work too) and make the game thread wait on the disk io thread to retrieve the data? Wouldn't that kill the whole point of having a separate thread to do it anyway?
So the idea I came up with was load the data for files on start up so when its needed it can be accessed from a collection. Take for example character files. I could loop through every single file in the ./data/players/ directory and put it in a map: the String key being the name of the player and PlayerData being the data loaded from the character file:
Code:
// every single character file in this map
private Map<String, PlayerData> playerFiles = new HashMap<String, PlayerData>();
public void decodeLogin() {
...
// time to load the character file! we don't have to load it here cause we did it on startup already
PlayerData data = playerFiles.get(player.getUsername());
// now we set the data like we'd normally do...
player.setPosition(data.getposition());
player.setAuthority(data.getAuthority());
player.setRunEnergy(data.getRunEnergy());
...
}
But wait! There's a problem with that. If a character logs out and logs back in there progress will only be saved to the last time that the server was started up! So I came up with this idea: for saving the character file, simply re-add it to the map and save the character on the disk io thread as normal!
Code:
playerFiles.put(player.getUsername(), new PlayerData() {
// ... some sort of implementation here to get all the correct data saved
});
// and here we use our disk io thread to save the actual file! (for the next startup)
GameEngine.getDiskPool().execute(new Runnable() {
@Override
public void run() {
// save the actual character file like we'd normally do
DiskFactory.getCharacter().write(....);
}
});
Right now I honestly can't see how this solution would be flawed, I told a friend about it earlier and he said it was a retarded idea but I'm convinced that its not. Would appreciate it if someone could tell me if its stupid (or not) and why (or why not)
If you think this is stupid how do you think it should be done? Would love to hear some alternatives.
thanks for reading!