java - Locking a file for an individual Thread within a VM -


I have several threads that are sorting my 'data' objects in files. File name object

 class data {org.joda.DateTime time is based on 2 fields; String title; Public string getFilename () {return time.toString () + '_' + title + ".xml"; } 

It is possible that 2 data objects will have the same 'time' and 'title', and similar file names.

It is acceptable, and I am happy for it or have to be saved (they are probably the same data object, if it is the same)

My problem is that two (or More) Threads are writing the file at the same time, due to which the faulty XML is.

I had a look at java.nio.channels.FileLock, but it is for VM-wide locking, and is not particularly suitable for thread locking.

I can synchronize on DataIO.class (but this would be the reason for a huge overhead because I really want to synchronize only on individual files).

Synchronizing the file object will be useless, because multiple file objects can represent the same system-file. / P>

code as follows:

 class dataio {public void writing articleToolfile (article article, string filename, boolean overwrite) throws IOException {file file = new file (file name); WriteArticleToFile (article, file, overwrite); } Public Zero Write DatataOphion throws data (file data, file file, boolean overwrite), IOException {if (file.exists ()) {if (overwrite) {if (! File.delete ()) {New IOEception (" Failed file, to overwrite: "+ file); }} And {new IOException ("file" + file + "already exists, and the overwrite flag is set to false."); }} File parentFile = file.getParentFile (); If (parentFile! = Null) {file.getParentFile (). Mkdirs (); } File.createNewFile (); If (! File.canWrite ()) {new IOE expansion ("You do not have permission to write to file:" + file); } FileOutputStream fos = New FileOutputStream (file, incorrect); Try {writeDataToStream (data, fos); Logger.debug ("The file was written successfully:" + file.getAbsolutePath ()); } Finally {fos.close (); }}} 

You can intern () string which is the filename. Then synchronize on the internal string.

class DataIO {public void writeArticleToFile (article article, string filename, boolean overwrite) throws IOException {synchronize (filename.intern ()) {file file = new file (file name); WriteArticleToFile (article, file, overwrite); }}

Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -