1/*
2 * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.nio.channels;
27
28import java.io.*;
29import java.nio.ByteBuffer;
30import java.nio.MappedByteBuffer;
31import java.nio.channels.spi.AbstractInterruptibleChannel;
32import java.util.Set;
33import java.util.HashSet;
34import java.util.Collections;
35
36/**
37 * A channel for reading, writing, mapping, and manipulating a file.
38 *
39 * <p> A file channel is a {@link SeekableByteChannel} that is connected to
40 * a file. It has a current <i>position</i> within its file which can
41 * be both {@link #position() <i>queried</i>} and {@link #position(long)
42 * <i>modified</i>}.  The file itself contains a variable-length sequence
43 * of bytes that can be read and written and whose current {@link #size
44 * <i>size</i>} can be queried.  The size of the file increases
45 * when bytes are written beyond its current size; the size of the file
46 * decreases when it is {@link #truncate </code><i>truncated</i><code>}.  The
47 * file may also have some associated <i>metadata</i> such as access
48 * permissions, content type, and last-modification time; this class does not
49 * define methods for metadata access.
50 *
51 * <p> In addition to the familiar read, write, and close operations of byte
52 * channels, this class defines the following file-specific operations: </p>
53 *
54 * <ul>
55 *
56 *   <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or
57 *   {@link #write(ByteBuffer, long) <i>written</i>} at an absolute
58 *   position in a file in a way that does not affect the channel's current
59 *   position.  </p></li>
60 *
61 *   <li><p> A region of a file may be {@link #map <i>mapped</i>}
62 *   directly into memory; for large files this is often much more efficient
63 *   than invoking the usual <tt>read</tt> or <tt>write</tt> methods.
64 *   </p></li>
65 *
66 *   <li><p> Updates made to a file may be {@link #force <i>forced
67 *   out</i>} to the underlying storage device, ensuring that data are not
68 *   lost in the event of a system crash.  </p></li>
69 *
70 *   <li><p> Bytes can be transferred from a file {@link #transferTo <i>to
71 *   some other channel</i>}, and {@link #transferFrom <i>vice
72 *   versa</i>}, in a way that can be optimized by many operating systems
73 *   into a very fast transfer directly to or from the filesystem cache.
74 *   </p></li>
75 *
76 *   <li><p> A region of a file may be {@link FileLock <i>locked</i>}
77 *   against access by other programs.  </p></li>
78 *
79 * </ul>
80 *
81 * <p> File channels are safe for use by multiple concurrent threads.  The
82 * {@link Channel#close close} method may be invoked at any time, as specified
83 * by the {@link Channel} interface.  Only one operation that involves the
84 * channel's position or can change its file's size may be in progress at any
85 * given time; attempts to initiate a second such operation while the first is
86 * still in progress will block until the first operation completes.  Other
87 * operations, in particular those that take an explicit position, may proceed
88 * concurrently; whether they in fact do so is dependent upon the underlying
89 * implementation and is therefore unspecified.
90 *
91 * <p> The view of a file provided by an instance of this class is guaranteed
92 * to be consistent with other views of the same file provided by other
93 * instances in the same program.  The view provided by an instance of this
94 * class may or may not, however, be consistent with the views seen by other
95 * concurrently-running programs due to caching performed by the underlying
96 * operating system and delays induced by network-filesystem protocols.  This
97 * is true regardless of the language in which these other programs are
98 * written, and whether they are running on the same machine or on some other
99 * machine.  The exact nature of any such inconsistencies are system-dependent
100 * and are therefore unspecified.
101 *
102 * <p> A file channel can be obtained from an
103 * existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link
104 * java.io.FileOutputStream#getChannel FileOutputStream}, or {@link
105 * java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking
106 * that object's <tt>getChannel</tt> method, which returns a file channel that
107 * is connected to the same underlying file. Where the file channel is obtained
108 * from an existing stream or random access file then the state of the file
109 * channel is intimately connected to that of the object whose <tt>getChannel</tt>
110 * method returned the channel.  Changing the channel's position, whether
111 * explicitly or by reading or writing bytes, will change the file position of
112 * the originating object, and vice versa. Changing the file's length via the
113 * file channel will change the length seen via the originating object, and vice
114 * versa.  Changing the file's content by writing bytes will change the content
115 * seen by the originating object, and vice versa.
116 *
117 * <a name="open-mode"></a> <p> At various points this class specifies that an
118 * instance that is "open for reading," "open for writing," or "open for
119 * reading and writing" is required.  A channel obtained via the {@link
120 * java.io.FileInputStream#getChannel getChannel} method of a {@link
121 * java.io.FileInputStream} instance will be open for reading.  A channel
122 * obtained via the {@link java.io.FileOutputStream#getChannel getChannel}
123 * method of a {@link java.io.FileOutputStream} instance will be open for
124 * writing.  Finally, a channel obtained via the {@link
125 * java.io.RandomAccessFile#getChannel getChannel} method of a {@link
126 * java.io.RandomAccessFile} instance will be open for reading if the instance
127 * was created with mode <tt>"r"</tt> and will be open for reading and writing
128 * if the instance was created with mode <tt>"rw"</tt>.
129 *
130 * <a name="append-mode"></a><p> A file channel that is open for writing may be in
131 * <i>append mode</i>, for example if it was obtained from a file-output stream
132 * that was created by invoking the {@link
133 * java.io.FileOutputStream#FileOutputStream(java.io.File,boolean)
134 * FileOutputStream(File,boolean)} constructor and passing <tt>true</tt> for
135 * the second parameter.  In this mode each invocation of a relative write
136 * operation first advances the position to the end of the file and then writes
137 * the requested data.  Whether the advancement of the position and the writing
138 * of the data are done in a single atomic operation is system-dependent and
139 * therefore unspecified.
140 *
141 * @see java.io.FileInputStream#getChannel()
142 * @see java.io.FileOutputStream#getChannel()
143 * @see java.io.RandomAccessFile#getChannel()
144 *
145 * @author Mark Reinhold
146 * @author Mike McCloskey
147 * @author JSR-51 Expert Group
148 * @since 1.4
149 */
150
151public abstract class FileChannel
152    extends AbstractInterruptibleChannel
153    implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel
154{
155    /**
156     * Initializes a new instance of this class.
157     */
158    protected FileChannel() { }
159
160    // -- Channel operations --
161
162    /**
163     * Reads a sequence of bytes from this channel into the given buffer.
164     *
165     * <p> Bytes are read starting at this channel's current file position, and
166     * then the file position is updated with the number of bytes actually
167     * read.  Otherwise this method behaves exactly as specified in the {@link
168     * ReadableByteChannel} interface. </p>
169     */
170    public abstract int read(ByteBuffer dst) throws IOException;
171
172    /**
173     * Reads a sequence of bytes from this channel into a subsequence of the
174     * given buffers.
175     *
176     * <p> Bytes are read starting at this channel's current file position, and
177     * then the file position is updated with the number of bytes actually
178     * read.  Otherwise this method behaves exactly as specified in the {@link
179     * ScatteringByteChannel} interface.  </p>
180     */
181    public abstract long read(ByteBuffer[] dsts, int offset, int length)
182        throws IOException;
183
184    /**
185     * Reads a sequence of bytes from this channel into the given buffers.
186     *
187     * <p> Bytes are read starting at this channel's current file position, and
188     * then the file position is updated with the number of bytes actually
189     * read.  Otherwise this method behaves exactly as specified in the {@link
190     * ScatteringByteChannel} interface.  </p>
191     */
192    public final long read(ByteBuffer[] dsts) throws IOException {
193        return read(dsts, 0, dsts.length);
194    }
195
196    /**
197     * Writes a sequence of bytes to this channel from the given buffer.
198     *
199     * <p> Bytes are written starting at this channel's current file position
200     * unless the channel is in append mode, in which case the position is
201     * first advanced to the end of the file.  The file is grown, if necessary,
202     * to accommodate the written bytes, and then the file position is updated
203     * with the number of bytes actually written.  Otherwise this method
204     * behaves exactly as specified by the {@link WritableByteChannel}
205     * interface. </p>
206     */
207    public abstract int write(ByteBuffer src) throws IOException;
208
209    /**
210     * Writes a sequence of bytes to this channel from a subsequence of the
211     * given buffers.
212     *
213     * <p> Bytes are written starting at this channel's current file position
214     * unless the channel is in append mode, in which case the position is
215     * first advanced to the end of the file.  The file is grown, if necessary,
216     * to accommodate the written bytes, and then the file position is updated
217     * with the number of bytes actually written.  Otherwise this method
218     * behaves exactly as specified in the {@link GatheringByteChannel}
219     * interface.  </p>
220     */
221    public abstract long write(ByteBuffer[] srcs, int offset, int length)
222        throws IOException;
223
224    /**
225     * Writes a sequence of bytes to this channel from the given buffers.
226     *
227     * <p> Bytes are written starting at this channel's current file position
228     * unless the channel is in append mode, in which case the position is
229     * first advanced to the end of the file.  The file is grown, if necessary,
230     * to accommodate the written bytes, and then the file position is updated
231     * with the number of bytes actually written.  Otherwise this method
232     * behaves exactly as specified in the {@link GatheringByteChannel}
233     * interface.  </p>
234     */
235    public final long write(ByteBuffer[] srcs) throws IOException {
236        return write(srcs, 0, srcs.length);
237    }
238
239
240    // -- Other operations --
241
242    /**
243     * Returns this channel's file position.  </p>
244     *
245     * @return  This channel's file position,
246     *          a non-negative integer counting the number of bytes
247     *          from the beginning of the file to the current position
248     *
249     * @throws  ClosedChannelException
250     *          If this channel is closed
251     *
252     * @throws  IOException
253     *          If some other I/O error occurs
254     */
255    public abstract long position() throws IOException;
256
257    /**
258     * Sets this channel's file position.
259     *
260     * <p> Setting the position to a value that is greater than the file's
261     * current size is legal but does not change the size of the file.  A later
262     * attempt to read bytes at such a position will immediately return an
263     * end-of-file indication.  A later attempt to write bytes at such a
264     * position will cause the file to be grown to accommodate the new bytes;
265     * the values of any bytes between the previous end-of-file and the
266     * newly-written bytes are unspecified.  </p>
267     *
268     * @param  newPosition
269     *         The new position, a non-negative integer counting
270     *         the number of bytes from the beginning of the file
271     *
272     * @return  This file channel
273     *
274     * @throws  ClosedChannelException
275     *          If this channel is closed
276     *
277     * @throws  IllegalArgumentException
278     *          If the new position is negative
279     *
280     * @throws  IOException
281     *          If some other I/O error occurs
282     */
283    public abstract FileChannel position(long newPosition) throws IOException;
284
285    /**
286     * Returns the current size of this channel's file.  </p>
287     *
288     * @return  The current size of this channel's file,
289     *          measured in bytes
290     *
291     * @throws  ClosedChannelException
292     *          If this channel is closed
293     *
294     * @throws  IOException
295     *          If some other I/O error occurs
296     */
297    public abstract long size() throws IOException;
298
299    /**
300     * Truncates this channel's file to the given size.
301     *
302     * <p> If the given size is less than the file's current size then the file
303     * is truncated, discarding any bytes beyond the new end of the file.  If
304     * the given size is greater than or equal to the file's current size then
305     * the file is not modified.  In either case, if this channel's file
306     * position is greater than the given size then it is set to that size.
307     * </p>
308     *
309     * @param  size
310     *         The new size, a non-negative byte count
311     *
312     * @return  This file channel
313     *
314     * @throws  NonWritableChannelException
315     *          If this channel was not opened for writing
316     *
317     * @throws  ClosedChannelException
318     *          If this channel is closed
319     *
320     * @throws  IllegalArgumentException
321     *          If the new size is negative
322     *
323     * @throws  IOException
324     *          If some other I/O error occurs
325     */
326    public abstract FileChannel truncate(long size) throws IOException;
327
328    /**
329     * Forces any updates to this channel's file to be written to the storage
330     * device that contains it.
331     *
332     * <p> If this channel's file resides on a local storage device then when
333     * this method returns it is guaranteed that all changes made to the file
334     * since this channel was created, or since this method was last invoked,
335     * will have been written to that device.  This is useful for ensuring that
336     * critical information is not lost in the event of a system crash.
337     *
338     * <p> If the file does not reside on a local device then no such guarantee
339     * is made.
340     *
341     * <p> The <tt>metaData</tt> parameter can be used to limit the number of
342     * I/O operations that this method is required to perform.  Passing
343     * <tt>false</tt> for this parameter indicates that only updates to the
344     * file's content need be written to storage; passing <tt>true</tt>
345     * indicates that updates to both the file's content and metadata must be
346     * written, which generally requires at least one more I/O operation.
347     * Whether this parameter actually has any effect is dependent upon the
348     * underlying operating system and is therefore unspecified.
349     *
350     * <p> Invoking this method may cause an I/O operation to occur even if the
351     * channel was only opened for reading.  Some operating systems, for
352     * example, maintain a last-access time as part of a file's metadata, and
353     * this time is updated whenever the file is read.  Whether or not this is
354     * actually done is system-dependent and is therefore unspecified.
355     *
356     * <p> This method is only guaranteed to force changes that were made to
357     * this channel's file via the methods defined in this class.  It may or
358     * may not force changes that were made by modifying the content of a
359     * {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by
360     * invoking the {@link #map map} method.  Invoking the {@link
361     * MappedByteBuffer#force force} method of the mapped byte buffer will
362     * force changes made to the buffer's content to be written.  </p>
363     *
364     * @param   metaData
365     *          If <tt>true</tt> then this method is required to force changes
366     *          to both the file's content and metadata to be written to
367     *          storage; otherwise, it need only force content changes to be
368     *          written
369     *
370     * @throws  ClosedChannelException
371     *          If this channel is closed
372     *
373     * @throws  IOException
374     *          If some other I/O error occurs
375     */
376    public abstract void force(boolean metaData) throws IOException;
377
378    /**
379     * Transfers bytes from this channel's file to the given writable byte
380     * channel.
381     *
382     * <p> An attempt is made to read up to <tt>count</tt> bytes starting at
383     * the given <tt>position</tt> in this channel's file and write them to the
384     * target channel.  An invocation of this method may or may not transfer
385     * all of the requested bytes; whether or not it does so depends upon the
386     * natures and states of the channels.  Fewer than the requested number of
387     * bytes are transferred if this channel's file contains fewer than
388     * <tt>count</tt> bytes starting at the given <tt>position</tt>, or if the
389     * target channel is non-blocking and it has fewer than <tt>count</tt>
390     * bytes free in its output buffer.
391     *
392     * <p> This method does not modify this channel's position.  If the given
393     * position is greater than the file's current size then no bytes are
394     * transferred.  If the target channel has a position then bytes are
395     * written starting at that position and then the position is incremented
396     * by the number of bytes written.
397     *
398     * <p> This method is potentially much more efficient than a simple loop
399     * that reads from this channel and writes to the target channel.  Many
400     * operating systems can transfer bytes directly from the filesystem cache
401     * to the target channel without actually copying them.  </p>
402     *
403     * @param  position
404     *         The position within the file at which the transfer is to begin;
405     *         must be non-negative
406     *
407     * @param  count
408     *         The maximum number of bytes to be transferred; must be
409     *         non-negative
410     *
411     * @param  target
412     *         The target channel
413     *
414     * @return  The number of bytes, possibly zero,
415     *          that were actually transferred
416     *
417     * @throws IllegalArgumentException
418     *         If the preconditions on the parameters do not hold
419     *
420     * @throws  NonReadableChannelException
421     *          If this channel was not opened for reading
422     *
423     * @throws  NonWritableChannelException
424     *          If the target channel was not opened for writing
425     *
426     * @throws  ClosedChannelException
427     *          If either this channel or the target channel is closed
428     *
429     * @throws  AsynchronousCloseException
430     *          If another thread closes either channel
431     *          while the transfer is in progress
432     *
433     * @throws  ClosedByInterruptException
434     *          If another thread interrupts the current thread while the
435     *          transfer is in progress, thereby closing both channels and
436     *          setting the current thread's interrupt status
437     *
438     * @throws  IOException
439     *          If some other I/O error occurs
440     */
441    public abstract long transferTo(long position, long count,
442                                    WritableByteChannel target)
443        throws IOException;
444
445    /**
446     * Transfers bytes into this channel's file from the given readable byte
447     * channel.
448     *
449     * <p> An attempt is made to read up to <tt>count</tt> bytes from the
450     * source channel and write them to this channel's file starting at the
451     * given <tt>position</tt>.  An invocation of this method may or may not
452     * transfer all of the requested bytes; whether or not it does so depends
453     * upon the natures and states of the channels.  Fewer than the requested
454     * number of bytes will be transferred if the source channel has fewer than
455     * <tt>count</tt> bytes remaining, or if the source channel is non-blocking
456     * and has fewer than <tt>count</tt> bytes immediately available in its
457     * input buffer.
458     *
459     * <p> This method does not modify this channel's position.  If the given
460     * position is greater than the file's current size then no bytes are
461     * transferred.  If the source channel has a position then bytes are read
462     * starting at that position and then the position is incremented by the
463     * number of bytes read.
464     *
465     * <p> This method is potentially much more efficient than a simple loop
466     * that reads from the source channel and writes to this channel.  Many
467     * operating systems can transfer bytes directly from the source channel
468     * into the filesystem cache without actually copying them.  </p>
469     *
470     * @param  src
471     *         The source channel
472     *
473     * @param  position
474     *         The position within the file at which the transfer is to begin;
475     *         must be non-negative
476     *
477     * @param  count
478     *         The maximum number of bytes to be transferred; must be
479     *         non-negative
480     *
481     * @return  The number of bytes, possibly zero,
482     *          that were actually transferred
483     *
484     * @throws IllegalArgumentException
485     *         If the preconditions on the parameters do not hold
486     *
487     * @throws  NonReadableChannelException
488     *          If the source channel was not opened for reading
489     *
490     * @throws  NonWritableChannelException
491     *          If this channel was not opened for writing
492     *
493     * @throws  ClosedChannelException
494     *          If either this channel or the source channel is closed
495     *
496     * @throws  AsynchronousCloseException
497     *          If another thread closes either channel
498     *          while the transfer is in progress
499     *
500     * @throws  ClosedByInterruptException
501     *          If another thread interrupts the current thread while the
502     *          transfer is in progress, thereby closing both channels and
503     *          setting the current thread's interrupt status
504     *
505     * @throws  IOException
506     *          If some other I/O error occurs
507     */
508    public abstract long transferFrom(ReadableByteChannel src,
509                                      long position, long count)
510        throws IOException;
511
512    /**
513     * Reads a sequence of bytes from this channel into the given buffer,
514     * starting at the given file position.
515     *
516     * <p> This method works in the same manner as the {@link
517     * #read(ByteBuffer)} method, except that bytes are read starting at the
518     * given file position rather than at the channel's current position.  This
519     * method does not modify this channel's position.  If the given position
520     * is greater than the file's current size then no bytes are read.  </p>
521     *
522     * @param  dst
523     *         The buffer into which bytes are to be transferred
524     *
525     * @param  position
526     *         The file position at which the transfer is to begin;
527     *         must be non-negative
528     *
529     * @return  The number of bytes read, possibly zero, or <tt>-1</tt> if the
530     *          given position is greater than or equal to the file's current
531     *          size
532     *
533     * @throws  IllegalArgumentException
534     *          If the position is negative
535     *
536     * @throws  NonReadableChannelException
537     *          If this channel was not opened for reading
538     *
539     * @throws  ClosedChannelException
540     *          If this channel is closed
541     *
542     * @throws  AsynchronousCloseException
543     *          If another thread closes this channel
544     *          while the read operation is in progress
545     *
546     * @throws  ClosedByInterruptException
547     *          If another thread interrupts the current thread
548     *          while the read operation is in progress, thereby
549     *          closing the channel and setting the current thread's
550     *          interrupt status
551     *
552     * @throws  IOException
553     *          If some other I/O error occurs
554     */
555    public abstract int read(ByteBuffer dst, long position) throws IOException;
556
557    /**
558     * Writes a sequence of bytes to this channel from the given buffer,
559     * starting at the given file position.
560     *
561     * <p> This method works in the same manner as the {@link
562     * #write(ByteBuffer)} method, except that bytes are written starting at
563     * the given file position rather than at the channel's current position.
564     * This method does not modify this channel's position.  If the given
565     * position is greater than the file's current size then the file will be
566     * grown to accommodate the new bytes; the values of any bytes between the
567     * previous end-of-file and the newly-written bytes are unspecified.  </p>
568     *
569     * @param  src
570     *         The buffer from which bytes are to be transferred
571     *
572     * @param  position
573     *         The file position at which the transfer is to begin;
574     *         must be non-negative
575     *
576     * @return  The number of bytes written, possibly zero
577     *
578     * @throws  IllegalArgumentException
579     *          If the position is negative
580     *
581     * @throws  NonWritableChannelException
582     *          If this channel was not opened for writing
583     *
584     * @throws  ClosedChannelException
585     *          If this channel is closed
586     *
587     * @throws  AsynchronousCloseException
588     *          If another thread closes this channel
589     *          while the write operation is in progress
590     *
591     * @throws  ClosedByInterruptException
592     *          If another thread interrupts the current thread
593     *          while the write operation is in progress, thereby
594     *          closing the channel and setting the current thread's
595     *          interrupt status
596     *
597     * @throws  IOException
598     *          If some other I/O error occurs
599     */
600    public abstract int write(ByteBuffer src, long position) throws IOException;
601
602
603    // -- Memory-mapped buffers --
604
605    /**
606     * A typesafe enumeration for file-mapping modes.
607     *
608     * @since 1.4
609     *
610     * @see java.nio.channels.FileChannel#map
611     */
612    public static class MapMode {
613
614        /**
615         * Mode for a read-only mapping.
616         */
617        public static final MapMode READ_ONLY
618            = new MapMode("READ_ONLY");
619
620        /**
621         * Mode for a read/write mapping.
622         */
623        public static final MapMode READ_WRITE
624            = new MapMode("READ_WRITE");
625
626        /**
627         * Mode for a private (copy-on-write) mapping.
628         */
629        public static final MapMode PRIVATE
630            = new MapMode("PRIVATE");
631
632        private final String name;
633
634        private MapMode(String name) {
635            this.name = name;
636        }
637
638        /**
639         * Returns a string describing this file-mapping mode.
640         *
641         * @return  A descriptive string
642         */
643        public String toString() {
644            return name;
645        }
646
647    }
648
649    /**
650     * Maps a region of this channel's file directly into memory.
651     *
652     * <p> A region of a file may be mapped into memory in one of three modes:
653     * </p>
654     *
655     * <ul type=disc>
656     *
657     *   <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer
658     *   will cause a {@link java.nio.ReadOnlyBufferException} to be thrown.
659     *   ({@link MapMode#READ_ONLY MapMode.READ_ONLY}) </p></li>
660     *
661     *   <li><p> <i>Read/write:</i> Changes made to the resulting buffer will
662     *   eventually be propagated to the file; they may or may not be made
663     *   visible to other programs that have mapped the same file.  ({@link
664     *   MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li>
665     *
666     *   <li><p> <i>Private:</i> Changes made to the resulting buffer will not
667     *   be propagated to the file and will not be visible to other programs
668     *   that have mapped the same file; instead, they will cause private
669     *   copies of the modified portions of the buffer to be created.  ({@link
670     *   MapMode#PRIVATE MapMode.PRIVATE}) </p></li>
671     *
672     * </ul>
673     *
674     * <p> For a read-only mapping, this channel must have been opened for
675     * reading; for a read/write or private mapping, this channel must have
676     * been opened for both reading and writing.
677     *
678     * <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>}
679     * returned by this method will have a position of zero and a limit and
680     * capacity of <tt>size</tt>; its mark will be undefined.  The buffer and
681     * the mapping that it represents will remain valid until the buffer itself
682     * is garbage-collected.
683     *
684     * <p> A mapping, once established, is not dependent upon the file channel
685     * that was used to create it.  Closing the channel, in particular, has no
686     * effect upon the validity of the mapping.
687     *
688     * <p> Many of the details of memory-mapped files are inherently dependent
689     * upon the underlying operating system and are therefore unspecified.  The
690     * behavior of this method when the requested region is not completely
691     * contained within this channel's file is unspecified.  Whether changes
692     * made to the content or size of the underlying file, by this program or
693     * another, are propagated to the buffer is unspecified.  The rate at which
694     * changes to the buffer are propagated to the file is unspecified.
695     *
696     * <p> For most operating systems, mapping a file into memory is more
697     * expensive than reading or writing a few tens of kilobytes of data via
698     * the usual {@link #read read} and {@link #write write} methods.  From the
699     * standpoint of performance it is generally only worth mapping relatively
700     * large files into memory.  </p>
701     *
702     * @param  mode
703     *         One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link
704     *         MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE
705     *         PRIVATE} defined in the {@link MapMode} class, according to
706     *         whether the file is to be mapped read-only, read/write, or
707     *         privately (copy-on-write), respectively
708     *
709     * @param  position
710     *         The position within the file at which the mapped region
711     *         is to start; must be non-negative
712     *
713     * @param  size
714     *         The size of the region to be mapped; must be non-negative and
715     *         no greater than {@link java.lang.Integer#MAX_VALUE}
716     *
717     * @return  The mapped byte buffer
718     *
719     * @throws NonReadableChannelException
720     *         If the <tt>mode</tt> is {@link MapMode#READ_ONLY READ_ONLY} but
721     *         this channel was not opened for reading
722     *
723     * @throws NonWritableChannelException
724     *         If the <tt>mode</tt> is {@link MapMode#READ_WRITE READ_WRITE} or
725     *         {@link MapMode#PRIVATE PRIVATE} but this channel was not opened
726     *         for both reading and writing
727     *
728     * @throws IllegalArgumentException
729     *         If the preconditions on the parameters do not hold
730     *
731     * @throws IOException
732     *         If some other I/O error occurs
733     *
734     * @see java.nio.channels.FileChannel.MapMode
735     * @see java.nio.MappedByteBuffer
736     */
737    public abstract MappedByteBuffer map(MapMode mode,
738                                         long position, long size)
739        throws IOException;
740
741
742    // -- Locks --
743
744    /**
745     * Acquires a lock on the given region of this channel's file.
746     *
747     * <p> An invocation of this method will block until the region can be
748     * locked, this channel is closed, or the invoking thread is interrupted,
749     * whichever comes first.
750     *
751     * <p> If this channel is closed by another thread during an invocation of
752     * this method then an {@link AsynchronousCloseException} will be thrown.
753     *
754     * <p> If the invoking thread is interrupted while waiting to acquire the
755     * lock then its interrupt status will be set and a {@link
756     * FileLockInterruptionException} will be thrown.  If the invoker's
757     * interrupt status is set when this method is invoked then that exception
758     * will be thrown immediately; the thread's interrupt status will not be
759     * changed.
760     *
761     * <p> The region specified by the <tt>position</tt> and <tt>size</tt>
762     * parameters need not be contained within, or even overlap, the actual
763     * underlying file.  Lock regions are fixed in size; if a locked region
764     * initially contains the end of the file and the file grows beyond the
765     * region then the new portion of the file will not be covered by the lock.
766     * If a file is expected to grow in size and a lock on the entire file is
767     * required then a region starting at zero, and no smaller than the
768     * expected maximum size of the file, should be locked.  The zero-argument
769     * {@link #lock()} method simply locks a region of size {@link
770     * Long#MAX_VALUE}.
771     *
772     * <p> Some operating systems do not support shared locks, in which case a
773     * request for a shared lock is automatically converted into a request for
774     * an exclusive lock.  Whether the newly-acquired lock is shared or
775     * exclusive may be tested by invoking the resulting lock object's {@link
776     * FileLock#isShared() isShared} method.
777     *
778     * <p> File locks are held on behalf of the entire Java virtual machine.
779     * They are not suitable for controlling access to a file by multiple
780     * threads within the same virtual machine.  </p>
781     *
782     * @param  position
783     *         The position at which the locked region is to start; must be
784     *         non-negative
785     *
786     * @param  size
787     *         The size of the locked region; must be non-negative, and the sum
788     *         <tt>position</tt>&nbsp;+&nbsp;<tt>size</tt> must be non-negative
789     *
790     * @param  shared
791     *         <tt>true</tt> to request a shared lock, in which case this
792     *         channel must be open for reading (and possibly writing);
793     *         <tt>false</tt> to request an exclusive lock, in which case this
794     *         channel must be open for writing (and possibly reading)
795     *
796     * @return  A lock object representing the newly-acquired lock
797     *
798     * @throws  IllegalArgumentException
799     *          If the preconditions on the parameters do not hold
800     *
801     * @throws  ClosedChannelException
802     *          If this channel is closed
803     *
804     * @throws  AsynchronousCloseException
805     *          If another thread closes this channel while the invoking
806     *          thread is blocked in this method
807     *
808     * @throws  FileLockInterruptionException
809     *          If the invoking thread is interrupted while blocked in this
810     *          method
811     *
812     * @throws  OverlappingFileLockException
813     *          If a lock that overlaps the requested region is already held by
814     *          this Java virtual machine, or if another thread is already
815     *          blocked in this method and is attempting to lock an overlapping
816     *          region
817     *
818     * @throws  NonReadableChannelException
819     *          If <tt>shared</tt> is <tt>true</tt> this channel was not
820     *          opened for reading
821     *
822     * @throws  NonWritableChannelException
823     *          If <tt>shared</tt> is <tt>false</tt> but this channel was not
824     *          opened for writing
825     *
826     * @throws  IOException
827     *          If some other I/O error occurs
828     *
829     * @see     #lock()
830     * @see     #tryLock()
831     * @see     #tryLock(long,long,boolean)
832     */
833    public abstract FileLock lock(long position, long size, boolean shared)
834        throws IOException;
835
836    /**
837     * Acquires an exclusive lock on this channel's file.
838     *
839     * <p> An invocation of this method of the form <tt>fc.lock()</tt> behaves
840     * in exactly the same way as the invocation
841     *
842     * <pre>
843     *     fc.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false) </pre>
844     *
845     * @return  A lock object representing the newly-acquired lock
846     *
847     * @throws  ClosedChannelException
848     *          If this channel is closed
849     *
850     * @throws  AsynchronousCloseException
851     *          If another thread closes this channel while the invoking
852     *          thread is blocked in this method
853     *
854     * @throws  FileLockInterruptionException
855     *          If the invoking thread is interrupted while blocked in this
856     *          method
857     *
858     * @throws  OverlappingFileLockException
859     *          If a lock that overlaps the requested region is already held by
860     *          this Java virtual machine, or if another thread is already
861     *          blocked in this method and is attempting to lock an overlapping
862     *          region of the same file
863     *
864     * @throws  NonWritableChannelException
865     *          If this channel was not opened for writing
866     *
867     * @throws  IOException
868     *          If some other I/O error occurs
869     *
870     * @see     #lock(long,long,boolean)
871     * @see     #tryLock()
872     * @see     #tryLock(long,long,boolean)
873     */
874    public final FileLock lock() throws IOException {
875        return lock(0L, Long.MAX_VALUE, false);
876    }
877
878    /**
879     * Attempts to acquire a lock on the given region of this channel's file.
880     *
881     * <p> This method does not block.  An invocation always returns
882     * immediately, either having acquired a lock on the requested region or
883     * having failed to do so.  If it fails to acquire a lock because an
884     * overlapping lock is held by another program then it returns
885     * <tt>null</tt>.  If it fails to acquire a lock for any other reason then
886     * an appropriate exception is thrown.
887     *
888     * <p> The region specified by the <tt>position</tt> and <tt>size</tt>
889     * parameters need not be contained within, or even overlap, the actual
890     * underlying file.  Lock regions are fixed in size; if a locked region
891     * initially contains the end of the file and the file grows beyond the
892     * region then the new portion of the file will not be covered by the lock.
893     * If a file is expected to grow in size and a lock on the entire file is
894     * required then a region starting at zero, and no smaller than the
895     * expected maximum size of the file, should be locked.  The zero-argument
896     * {@link #tryLock()} method simply locks a region of size {@link
897     * Long#MAX_VALUE}.
898     *
899     * <p> Some operating systems do not support shared locks, in which case a
900     * request for a shared lock is automatically converted into a request for
901     * an exclusive lock.  Whether the newly-acquired lock is shared or
902     * exclusive may be tested by invoking the resulting lock object's {@link
903     * FileLock#isShared() isShared} method.
904     *
905     * <p> File locks are held on behalf of the entire Java virtual machine.
906     * They are not suitable for controlling access to a file by multiple
907     * threads within the same virtual machine.  </p>
908     *
909     * @param  position
910     *         The position at which the locked region is to start; must be
911     *         non-negative
912     *
913     * @param  size
914     *         The size of the locked region; must be non-negative, and the sum
915     *         <tt>position</tt>&nbsp;+&nbsp;<tt>size</tt> must be non-negative
916     *
917     * @param  shared
918     *         <tt>true</tt> to request a shared lock,
919     *         <tt>false</tt> to request an exclusive lock
920     *
921     * @return  A lock object representing the newly-acquired lock,
922     *          or <tt>null</tt> if the lock could not be acquired
923     *          because another program holds an overlapping lock
924     *
925     * @throws  IllegalArgumentException
926     *          If the preconditions on the parameters do not hold
927     *
928     * @throws  ClosedChannelException
929     *          If this channel is closed
930     *
931     * @throws  OverlappingFileLockException
932     *          If a lock that overlaps the requested region is already held by
933     *          this Java virtual machine, or if another thread is already
934     *          blocked in this method and is attempting to lock an overlapping
935     *          region of the same file
936     *
937     * @throws  IOException
938     *          If some other I/O error occurs
939     *
940     * @see     #lock()
941     * @see     #lock(long,long,boolean)
942     * @see     #tryLock()
943     */
944    public abstract FileLock tryLock(long position, long size, boolean shared)
945        throws IOException;
946
947    /**
948     * Attempts to acquire an exclusive lock on this channel's file.
949     *
950     * <p> An invocation of this method of the form <tt>fc.tryLock()</tt>
951     * behaves in exactly the same way as the invocation
952     *
953     * <pre>
954     *     fc.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre>
955     *
956     * @return  A lock object representing the newly-acquired lock,
957     *          or <tt>null</tt> if the lock could not be acquired
958     *          because another program holds an overlapping lock
959     *
960     * @throws  ClosedChannelException
961     *          If this channel is closed
962     *
963     * @throws  OverlappingFileLockException
964     *          If a lock that overlaps the requested region is already held by
965     *          this Java virtual machine, or if another thread is already
966     *          blocked in this method and is attempting to lock an overlapping
967     *          region
968     *
969     * @throws  IOException
970     *          If some other I/O error occurs
971     *
972     * @see     #lock()
973     * @see     #lock(long,long,boolean)
974     * @see     #tryLock(long,long,boolean)
975     */
976    public final FileLock tryLock() throws IOException {
977        return tryLock(0L, Long.MAX_VALUE, false);
978    }
979
980}
981