• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to lock a file?  RSS feed

 
Mark Guo
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys
I encountered a problem in linux System, when my server side writing a file name "A".txt not finished, the user side begin to read my "A".txt file, so the user get the file not perfect, please give me a solution to solve this problem and how to make the file be thread safe?
Thanks in advance!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're creating a file and you don't want anybody else to read it until you're done, the easiest and most portable approach is to create it as a temp file, write it completely, and then rename it to its "real" name.
 
Rob Spoor
Sheriff
Posts: 20903
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem with Linux and Unix is that they don't lock files like Windows does. While Windows will surely complain if you try to remove a file that's still opened by some application, Linux and Unix will delete it without a problem.

Apart from using temporary files like Jeff described, you can also create temporary utility files. I've seen applications that create an A.txt.lck file for the time the file should be locked, then delete this temporary file when done. While this file exist the user side should not touch the A.txt file. Using a WatchService (since Java 7) can even help you get notified when the .lck file is deleted.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:
Apart from using temporary files like Jeff described, you can also create temporary utility files. I've seen applications that create an A.txt.lck file for the time the file should be locked, then delete this temporary file when done. While this file exist the user side should not touch the A.txt file. Using a WatchService (since Java 7) can even help you get notified when the .lck file is deleted.


The advantage of the .lck file is that it more closely resembles a file lock in structure. It lets you write code like "apply lock/remove lock". The disadvantage is that it doesn't stop arbitrary processes from accessing A.txt. It only matters to those processes that know about the .lck file and choose to honor it.
 
Rob Spoor
Sheriff
Posts: 20903
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very true indeed.
 
Mark Guo
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!