I'm looking for a synchronisation method to ensure my back-end data (xml file) is kept intact during multiple client access.
I'm using jaxb to read and write to and from the file. I want to make sure that when a client reads or writes information to the xml file that no other clients are accessing it at the same time.
I've had a read about a ReadWriteLock and wondering if this is the best solution? Obviously clients should run some sort of query to see if anything is currently being writtern to the file, and if not then go ahead with the read/write?
I'm kind of new to java to excuse my ignorance!
Thanks
Your problem involves different "clients" - presumably applications running in different JVMs.
If this is the case, the ReadWriteLock class is not going to help. That class is for doing synchronization of different threads within a single JVM.
What you actually want is the FileLock class. This locks a file or region of a file against access by another JVM. You need to do something like this:
FileInputStream fis = new FileInputStream("someFile");
FileChannel fc = fis.getChannel();
FileLock fl = fc.lock(); // or tryLock(), or etc
// do stuff
fl.release();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With