How do I prevent a file from becoming corrupt due to simultaneous access?
While working with files, it is important to lock them for single threaded access. If you do not, it is possible that your application will try to perform simultaneous read or write operations on the file. This could cause all kinds of undesirable results, including file corruption. By wrapping all file access code in a <cflock> tag that is uniquely named for each file, you insure that your file data only be accessed by one process at a time.
The following code shows a sample use of a <cflock> tag that could be used to protect a file transaction:
<!--- Insert file transaction --->
</cflock>
Note the name of the lock. By setting this to something related to the particular file you will be working with, you can better insure that the next portion of code that will work with this file will use the same lock.
This question was written by Jeremy Petersen.
It was last updated on January 31, 2006 at 9:17:50 AM EST.
CFML Referenced
Categories
Comments
Comment made by Dave Carabetta on January 31, 2006 at 12:13 PM
One important thing to point out is that this only works if the only system interacting with this file is this ColdFusion instance. If a non-ColdFusion application (such as a database) or even another ColdFusion instance tries to access the file, it will have no idea about the original instance's cflock.