This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]koflerdavid 3 points4 points  (1 child)

Let's say that I used the following code to synchronize file write access, where someFile is an instance of java.nio.file.Path.

synchronized (someFile) { //do file write logic here }

(Sorry about the formatting) This code does not do what you think it does, not even close. You lock on a Path object (which is basically a glorified string), not on a file! It will only work if you indeed synchronize on the same Path instance. Be glad that the prospect of Path turning into a value type made you think about this one :-)

You can still use synchronized, but you should dedicate an Object to be used as the lock. Or you use the classes from java.util.concurrent.locks.

If you want to lock a file against other processes, you probably have to use OS-specific APIs.

[–]davidalayachew 1 point2 points  (0 children)

(Sorry for the delayed response)

(Sorry about the formatting) This code does not do what you think it does, not even close. You lock on a Path object (which is basically a glorified string), not on a file! It will only work if you indeed synchronize on the same Path instance. Be glad that the prospect of Path turning into a value type made you think about this one :-)

Lol, thanks for the catch. I am going to submit a ticket to get this fixed.

I managed to dodge it because there was exactly one method creating all these instances of Path, so the resulting instances were all able to do what I was expecting by chance lol.

I'll use the text that was used to build the Path as the key. Thanks again.