Reputation: 7106
I need to write some data in a temporary file and to store this file in a directory A. I use the File.createTempFile method to do this. But, there is a thread that periodically polls the directory A to check if there are temporary files to process.
// create a temporary file that will contain the data
newTmpFile = File.createTempFile("prefix", recoverFileExt, new File(
recoverDirectory));
// the file is set to non readable, so the recovery thread cannot
// access it
newTmpFile.setReadable(false);
//write data into the file
// the file is written, it is set to readable so the recovery thread
// can now access it
newTmpFile.setReadable(true);
The problem is that I don't want the recovery thread to access the file before the write operation is done. So, I use this mechanism : I create the file, set it as non readable, write to it then set it readable and close it. The problem is that just after the file creation, the file is still readable and the thread can access it.
So, I wanted to know if there is a possibility to set the file as non readable at its creation or if you have other solutions.
Thanks
Upvotes: 2
Views: 144
Reputation: 533492
If the thread is in the same process, you can keep a counter which controls how much data has been safely written. This allows you to process the recovery journal almost as soon as it has been written.
Upvotes: 0
Reputation: 1268
I would bypass it by creating file with a special name that the thread will ignore. Then you firstly rename it and then change it to readable. So you will have two checks - whether the file is nonreadable and whether it has a special name..
Upvotes: 0
Reputation: 33068
Create an Index of the Files
You should not use the file system as a locking mechanism in this way. Aix's solution with a different filename would work, but it isn't ideal.
A better solution would be to have an index of the files loaded in memory somewhere that both threads can access. Anytime you create a file for processing, once it's complete and ready to be processed, add it to the index. Then the recovery thread would only access files which it is given in the index to process.
This index would effectively be a work queue for the recovery thread.
Upvotes: 0
Reputation: 25873
IMHO this is not the way to do it. Use semaphores/mutexes to control thread synchronisation. Trying to sync threads using a file is a bad habit and will result in more bugs later.
Upvotes: 0
Reputation: 500307
My suggestion would be to first give the file a different name (e.g. using a different prefix) and rename it after it's been written.
This way the recovery thread can differentiate between partially- and fully-written files and only process the latter.
Upvotes: 5