Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

8
  • 29
    More importantly, understand that the lock of for the JVM, and not suitable for locking the file for access by individual threads within a single JVM. Commented Sep 25, 2008 at 7:00
  • 11
    You need a writable stream (i.e. FileOutputStream). Commented Apr 16, 2013 at 12:55
  • 1
    @Javier Do you? I've not tried. Nothing jumps out of the API docs saying that is a requirement. FileOutputStream isn't going to be much use for a Reader. Commented Apr 17, 2013 at 12:52
  • 20
    Yes, I tried it and it throws NonWritableChannelException, because lock() attempts to acquire an exclusive lock, but that requires write access. If you have an input stream, you can use lock(0L, Long.MAX_VALUE, false) which acquires a shared lock and only requires a read access. You can also use a RandomAccessFile opened in read-write mode if you want a exclusive lock while reading... but that would forbid concurrent readers. Commented Apr 17, 2013 at 14:16
  • 7
    @Javier I think you mean to say lock(0L, Long.MAX_VALUE, true), not lock(0L, Long.MAX_VALUE, false). the last argument there is boolean shared docs.oracle.com/javase/8/docs/api/java/nio/channels/… Commented Jan 23, 2017 at 17:18