Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Read/Write file

 
Mike Landis
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have a situation where multiple application
instances are reading and writing (maybe) to same file simultaneously. JDK is version 1.3.x and in my case there is no database available.
How should I handle possible file corruptions?
Any patterns/techniques available?
mike
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this situation I generally create a "lock file", which is basically an empty file in the same directory as the file I want to access. The file name is the same as the name of the file I want to access with a "_" prepended to it.
My code then tries to create this file. If it receives an I/O error stating that the file already exists then it continues looping. Otherwise it creates the file, does what it needs to the source file, and then deletes the lock file.
Of course, there are several design issues with this:
What if the application stops while the lock file is there and the lock file does not get removed? Someone would have to manually remove that lock file.
Do you have permissions to create a file in the directory? Usually the answer is "yes," but theoretically you might not.
It's not a perfect design, but then again, not having a database is not a perfect situation
 
Mike Landis
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, thank you!
I also try this approach.
Br
Mike
Originally posted by Joel McNary:
In this situation I generally create a "lock file", which is basically an empty file in the same directory as the file I want to access. The file name is the same as the name of the file I want to access with a "_" prepended to it.
My code then tries to create this file. If it receives an I/O error stating that the file already exists then it continues looping. Otherwise it creates the file, does what it needs to the source file, and then deletes the lock file.
Of course, there are several design issues with this:
What if the application stops while the lock file is there and the lock file does not get removed? Someone would have to manually remove that lock file.
Do you have permissions to create a file in the directory? Usually the answer is "yes," but theoretically you might not.
It's not a perfect design, but then again, not having a database is not a perfect situation
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic