1

MY Situation

I have a process which does FTP and another process which Emails.

While I am done with FTP I want to email a success notification. So the email process is watching for a new file pr configuration file to come in to a particular directory

The FTP process creates a file appropriate for the email process which is more or less list of emails in a property file.

The problem I am facing is while I create the file and write it. The email process which detects a new file and reads it before or while the file is being written. Therefore it accesses only null parameters. While I can put a sleep on top of Email process it would not work for all cases and it will hinder for other people who have finished files.

What can I use to -create a property file which cannot be read untill it is completely written -or create a property file with a lock which can be unlocked from another process if need be.

What are my choices?

As far as now: - I have tried using apache commons configuration to setProperty it created the same old read/write access problem - I created a property =new property and used store method to create the file. Even then the Email process would read before it is completely

FYI: Email Process had WatchDirectory and reads whenever a new file is created.

2 Answers 2

5

You need to do an operation which is "atomic" with regards to the file system. Write the file under another filename (such as .tmpfoobar) and when you're finished, close it and do a File.renameTo() to move it into place. Renames are atomic.

Sign up to request clarification or add additional context in comments.

Comments

0

Not sure why you're being downvoted, as this seems like a worthwhile question.

Martin suggests using a file rename to accomplish this: first write the file with a temporary name and then rename it. Then, if the other process/thread only accesses the renamed files then you should be good to go as re-names are indeed atomic.

An alternative approach if you are using a multithreaded application is to use a mutex of some sort to ensure that the reading thread does not read until the file has been closed by the writing thread.

This page and others on javamex.com have some pretty good explanations of Java concurrent programming:

http://www.javamex.com/tutorials/synchronization_concurrency_1.shtml

1 Comment

Probably been down voted as files are not a good way to communicate between processes. I assume the OP knows this and is trying to find the best solution given the constraints he has.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.