Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 710
constantlearner Avatar asked Dec 22 '25 23:12

constantlearner


2 Answers

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.

like image 127
Jeff Foster Avatar answered Dec 24 '25 13:12

Jeff Foster


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()
like image 32
AlexR Avatar answered Dec 24 '25 12:12

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!