I have a file that simulates a 10X3 array. The first column is a serial id number witch is unique so I can tell apart each row. I am asking if it is possible to synchronize 2 threads to write in the same file, LOCKING them based on the row they are (thread 1 can't access the file if thread 2 writes in the same row thread 1 wants to write, they can simultaneously write in other rows). I have a Lock array with 10 ReentrantLock() items and each Lock item will be locking the corresponding id row (They get the locks before they search the file for the ID). The simple way is to load the file into an array. BUT I want to know if I can achieve that within the file. I don't know in depth how files work in java, but my main concern is that when they write simultaneously in the file, the thread that ends last will give the final value of the file, so any changes that have been done so far by other the other thread will be erased, because the file needs to be saved.
Asked
Active
Viewed 598 times
-1
-
Why do you need to write concurrently to the file? Wouldn't it be simpler to perform the changes sequentially? – Adriaan Koster Apr 02 '15 at 15:28
-
I don't believe that Java's `OutputStream` supports writing partway through a file like this. There may be another way to do this, but in my 10 years of Java experience in industry, it's never been necessary or practical. Another thing to consider is that disk will always be slower than CPU, so multithreading the write won't gain you any speedup. I think the only way you would get speedup is if you were writing multiple files to multiple independent disks. – CodeBlind Apr 02 '15 at 15:29
-
[This](http://stackoverflow.com/q/7565034/2675154) is a similar question for C++, but maybe the answers give you some general insight. – honk Apr 02 '15 at 15:32
-
Actually the file is a lot bigger than that and the changes to the file are a huge number. I just gave that example cause it is simpler. The question remains the same. Also I want to test the efficiency between some policies. – Grigoris Savvas Apr 02 '15 at 15:33
1 Answers
1
With one file this won't be possible I think for the reason you mentioned.
If you really want to do this with plain text files you could create one file for each row. Another option would be to use Document. It should be easy to parse the document into a plain text file once all work is done.
The easiest solution is to use a database in my opinion particularly if there's a chance the array will grow in size later.

Frank Andres
- 146
- 5
-
I think i would go with the array. Of course a database would be the best idea, but i want this for a project. And i was thinking those 2 ways (because instead of a database we have the file). Maybe when I finish it, i will test the other method and post some results :) – Grigoris Savvas Apr 02 '15 at 16:01