Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - write two files atomically

I am facing a problem for which I don't have a clean solution. I am writing a Java application and the application stores certain data in a limited set of files. We are not using any database, just plain files. Due to some user-triggered action, certain files needs to be changed. I need this to be a all-or-nothing operation. That is, either all files are updated, or none of them. It is disastrous if for example 2 of the 5 files are changed, while the other 3 are not due to some IOException.

What is the best strategy to accomplish this? Is embedding an in-memory database, such as hsqldb, a good reason to get this kind of atomicity/transactional behavior?

Thanks a lot!

like image 989
user1284566 Avatar asked Mar 21 '12 22:03

user1284566


1 Answers

A safe approach IMO is:

  1. Backup
  2. Maintain a list of processed files
  3. On exception, restore the ones that have been processed with the backed up one.

It depends on how heavy it is going to be and the limits for time and such.

like image 74
Sully Avatar answered Sep 22 '22 14:09

Sully