newbieLinuxCpp
newbieLinuxCpp

Reputation: 486

How to synchronize file writing to achieve maximum concurrency between threads Java

I have 10 text files, that I use to store records. In my application, I have couple of operations, e.g write to file and edit file (if the specified line is found I create a temp file and transfer all info there, then delete the old and rename the temp file).

All my clients will have access to the 10 text files, so I want synchronize their activities to maintain data consistency.

I want to lock or synchronize a file if a client is editing or writing, say f1.txt so no other can write/edit to it and increase concurrency by letting another client to edit f2.txt in the same time.

public void writeToFile(String pathname){
File f1 = new File(pathname)
synchronize (f1) {.. // do something}
}

My problem here is that am creating a new file everytime with a specific path.

Please I would appreciate any guidance and help, am you to this.

Thanks

Upvotes: 2

Views: 3834

Answers (1)

Charles Forsythe
Charles Forsythe

Reputation: 1861

If I understand correctly, you want to synchronize on a particular file path (and the file system is not enforcing this in a way you like). You are correct the the File object will not work. What you need to synchronize on is the name of the file.

public void writeToFile(String pathname){
File f1 = new File(pathname)
synchronize (f1.getCanonicalPath().intern()) {.. // do something}
}

The getCanonicalPath method will return the same String value for any two File objects that reference the same path. For example, if ../logs/mylog.txt and /var/spool/logs/mylog.txt are the same file, they will have the same canonical path.

The intern method returns the same reference for any two String object with the same value. So, what you end up locking on is a singleton instance of the canonical path for the file.

I think that meets your needs.

Upvotes: 8

Related Questions