Only 48 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Read/Write files from different threads in same JVM  RSS feed

 
Doug Morand
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the best way to handle read/write of files within the same JVM? I thought I should be using file locks, but based on what I read for FileLock it looks like this isn't suitable for threads in the same JVM.
From FileLock javadoc:
"File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine."

I have 2 threads, one which is creating files, and the other which is reading those files and will move them to another location once finished. What's the best way to handle this so that my thread which reads files doesn't run into a situation where it tries to read a file which Thread1 is trying to write still. Should I just create the File object and check the canWrite() method to make sure I can get access to the file?
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, no, the best way would be for the two threads to talk to each other directly rather than relying on the file system to synchronize their actions.

You've got what sounds like a pretty standard producer/consumer setup. The usual way this works is for the producer to notify the consumer when it has completed the production of a unit of work, and for the consumer to wait for these notifications. Nowadays it's common to use a BlockingQueue of some kind; the API documentation has an example of how you might do that.
 
Doug Morand
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent thanks, let me check that out.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!