Multiple reader file java
I'm currently using Java 6 with Spring 3.
I have some processes that are reading the same file, in this case is XML file.
Also, this processes need to update the content of that file which is I need to update a date.
The process run simultaneously, so there's a possibility they will read and try to write at the same time.
I heard about ReadWriteLock, which can have multiple reader and only 1 writer. I'm considering that at the moment. But because the process is running quickyly,
There will be a scenario when process A is currently writing an update, and process B is waiting and another process C is waiting for writing the update. Process B might be just an old update 开发者_如何学JAVAif process B is updating the same element.
Is there any idea how can I achieve this?
Thanks,
If all of the "processes" are threads, use synchronization. That is exactly what this is for. ReadWriteLock won't protect the file itself anyhow; it is for coordinating shared access to objects in memory.
Something like this pseudo-code:
class XmlDatabase {
Document doc = readXml();
synchronized Date readDate() {
Date _date = getDateFromDoc(doc);
return _date;
}
synchronized void writeDate(Date _date) {
addDateToDoc(_date);
writeDocToFile(doc);
}
}
A lot of people will tell you that synchronization is slow, etc. Unless you're implementing something that is meant to be massively concurrent using synchronization primitives will work fine. You can always optimize with java.util.concurrent later on if needed. The simplicity and readability of using plain synchronization is worth it. If you need to give other processes access to the data, just wrap the database class with RMI or some other networking solution.
精彩评论