constantlearner
constantlearner

Reputation: 5247

Thread Safety of files

I have many applications writing to my file in concurrent in java.I want to make this operation concurrent and also want my file to preserve order.I have Thread 1 writing from website 1

Thread 2 writing from website 2

Thread 3 writing from website 3

And i want to preserve order.

How can i do this Thanks

Upvotes: 2

Views: 5189

Answers (2)

AlexR
AlexR

Reputation: 115328

You can use regular synchronization mechanism. Create file repository that contains references to java.io.File objects. It will expose API like getFile(String path). Every time you want to access file do the following:

File file = FileRepository.getFile("foo.txt");
synchronized(file) {
  // perform any manipulations. 
}

Other way to synchronize access to files is:

FileChannel.lock()

Upvotes: 5

Jeff Foster
Jeff Foster

Reputation: 44696

Use a Queue to represent operations to the file and make sure you take from the queue in the appropriate order (first-in-first-out). You could treat this as a producer consumer problem. You have multiple threads grabbing data, and a single consumer writing that data to disk.

Upvotes: 6

Related Questions