• Post Reply Bookmark Topic Watch Topic
  • New Topic

Avoid multiple accesses to a file  RSS feed

 
chandana nannapaneni
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a file "test.xml" which contains <result job="0"/>
Now, I have 2 java programs which runs parallely.
Each of the program, needs to access the test.xml, take the value of job and immediately increment the value of job so that at any point of time the job numbers should not be the same.

Now the problem is that both the programs are accessing the file at the same time and both are getting the same job number. What I want to do is that while one program is accessing the file, other programs should wait.
Can anyone tell me how can I do this?

 
Kumaravel Elangovan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

You can put the code to read the file in synchronization block, so that when one java class reads the file another one can't read it.

Regards,
Kumar
 
Rob Spoor
Sheriff
Posts: 20903
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ehm, that's not really going to work; other programs can still access the file.

FileLock is the way to go. You can use it in combination with FileChannel and RandomAccessFile:
The truncate is really only needed when you are writing to the file and the file will be smaller than before.

Now you can't use FileInputStream, FileOutputStream, FileReader or FileWriter anymore. Fortunately, java.nio.channel.Channels can help you out by creating InputStream, OutputStream, Reader and Writer wrappers around your FileChannel (which is both a ReadableByteChannel and a WritableByteChannel). All you need to do when creating a Reader or Writer is provide the charset, but the easiest is simply using Charset.defaultCharset().

For instance, reading and writing with the channel:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!