1 /*
   2  * Copyright (c) 2000, 2023, 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 
  26 package java.nio.channels;
  27 
  28 import java.io.IOException;
  29 import java.lang.foreign.Arena;
  30 import java.lang.foreign.MemorySegment;
  31 import java.nio.ByteBuffer;
  32 import java.nio.MappedByteBuffer;
  33 import java.nio.channels.spi.AbstractInterruptibleChannel;
  34 import java.nio.file.FileAlreadyExistsException;
  35 import java.nio.file.OpenOption;
  36 import java.nio.file.Path;
  37 import java.nio.file.StandardOpenOption;
  38 import java.nio.file.attribute.FileAttribute;
  39 import java.nio.file.spi.FileSystemProvider;
  40 import java.util.Set;
  41 import java.util.HashSet;
  42 import java.util.Collections;
  43 import jdk.internal.javac.PreviewFeature;
  44 
  45 /**
  46  * A channel for reading, writing, mapping, and manipulating a file.
  47  *
  48  * <p> A file channel is a {@link SeekableByteChannel} that is connected to
  49  * a file. It has a current <i>position</i> within its file which can
  50  * be both {@link #position() <i>queried</i>} and {@link #position(long)
  51  * <i>modified</i>}.  The file itself contains a variable-length sequence
  52  * of bytes that can be read and written and whose current {@link #size
  53  * <i>size</i>} can be queried.  The size of the file increases
  54  * when bytes are written beyond its current size; the size of the file
  55  * decreases when it is {@link #truncate <i>truncated</i>}.  The
  56  * file may also have some associated <i>metadata</i> such as access
  57  * permissions, content type, and last-modification time; this class does not
  58  * define methods for metadata access.
  59  *
  60  * <p> In addition to the familiar read, write, and close operations of byte
  61  * channels, this class defines the following file-specific operations: </p>
  62  *
  63  * <ul>
  64  *
  65  *   <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or
  66  *   {@link #write(ByteBuffer, long) <i>written</i>} at an absolute
  67  *   position in a file in a way that does not affect the channel's current
  68  *   position.  </p></li>
  69  *
  70  *   <li><p> A region of a file may be {@link #map <i>mapped</i>}
  71  *   directly into memory; for large files this is often much more efficient
  72  *   than invoking the usual {@code read} or {@code write} methods.
  73  *   </p></li>
  74  *
  75  *   <li><p> Updates made to a file may be {@link #force <i>forced
  76  *   out</i>} to the underlying storage device, ensuring that data are not
  77  *   lost in the event of a system crash.  </p></li>
  78  *
  79  *   <li><p> Bytes can be transferred from a file {@link #transferTo <i>to
  80  *   some other channel</i>}, and {@link #transferFrom <i>vice
  81  *   versa</i>}, in a way that can be optimized by many operating systems
  82  *   into a very fast transfer directly to or from the filesystem cache.
  83  *   </p></li>
  84  *
  85  *   <li><p> A region of a file may be {@link FileLock <i>locked</i>}
  86  *   against access by other programs.  </p></li>
  87  *
  88  * </ul>
  89  *
  90  * <p> File channels are safe for use by multiple concurrent threads.  The
  91  * {@link Channel#close close} method may be invoked at any time, as specified
  92  * by the {@link Channel} interface.  Only one operation that involves the
  93  * channel's position or can change its file's size may be in progress at any
  94  * given time; attempts to initiate a second such operation while the first is
  95  * still in progress will block until the first operation completes.  Other
  96  * operations, in particular those that take an explicit position, may proceed
  97  * concurrently; whether they in fact do so is dependent upon the underlying
  98  * implementation and is therefore unspecified.
  99  *
 100  * <p> The view of a file provided by an instance of this class is guaranteed
 101  * to be consistent with other views of the same file provided by other
 102  * instances in the same program.  The view provided by an instance of this
 103  * class may or may not, however, be consistent with the views seen by other
 104  * concurrently-running programs due to caching performed by the underlying
 105  * operating system and delays induced by network-filesystem protocols.  This
 106  * is true regardless of the language in which these other programs are
 107  * written, and whether they are running on the same machine or on some other
 108  * machine.  The exact nature of any such inconsistencies are system-dependent
 109  * and are therefore unspecified.
 110  *
 111  * <p> A file channel is created by invoking one of the {@link #open open}
 112  * methods defined by this class. A file channel can also be obtained from an
 113  * existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link
 114  * java.io.FileOutputStream#getChannel FileOutputStream}, or {@link
 115  * java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking
 116  * that object's {@code getChannel} method, which returns a file channel that
 117  * is connected to the same underlying file. Where the file channel is obtained
 118  * from an existing stream or random access file then the state of the file
 119  * channel is intimately connected to that of the object whose {@code getChannel}
 120  * method returned the channel.  Changing the channel's position, whether
 121  * explicitly or by reading or writing bytes, will change the file position of
 122  * the originating object, and vice versa. Changing the file's length via the
 123  * file channel will change the length seen via the originating object, and vice
 124  * versa.  Changing the file's content by writing bytes will change the content
 125  * seen by the originating object, and vice versa. Closing the channel will
 126  * close the originating object.
 127  *
 128  * <a id="open-mode"></a> <p> At various points this class specifies that an
 129  * instance that is "open for reading," "open for writing," or "open for
 130  * reading and writing" is required.  A channel obtained via the {@link
 131  * java.io.FileInputStream#getChannel getChannel} method of a {@link
 132  * java.io.FileInputStream} instance will be open for reading.  A channel
 133  * obtained via the {@link java.io.FileOutputStream#getChannel getChannel}
 134  * method of a {@link java.io.FileOutputStream} instance will be open for
 135  * writing.  Finally, a channel obtained via the {@link
 136  * java.io.RandomAccessFile#getChannel getChannel} method of a {@link
 137  * java.io.RandomAccessFile} instance will be open for reading if the instance
 138  * was created with mode {@code "r"} and will be open for reading and writing
 139  * if the instance was created with mode {@code "rw"}.
 140  *
 141  * <a id="append-mode"></a><p> A file channel that is open for writing may be in
 142  * <i>append mode</i>, for example if it was obtained from a file-output stream
 143  * that was created by invoking the {@link
 144  * java.io.FileOutputStream#FileOutputStream(java.io.File,boolean)
 145  * FileOutputStream(File,boolean)} constructor and passing {@code true} for
 146  * the second parameter.  In this mode each invocation of a relative write
 147  * operation first advances the position to the end of the file and then writes
 148  * the requested data.  Whether the advancement of the position and the writing
 149  * of the data are done in a single atomic operation is system-dependent and
 150  * therefore unspecified.  In this mode the behavior of the method to
 151  * {@linkplain #write(ByteBuffer,long) write at a given position} is also
 152  * system-dependent.
 153  *
 154  * @see java.io.FileInputStream#getChannel()
 155  * @see java.io.FileOutputStream#getChannel()
 156  * @see java.io.RandomAccessFile#getChannel()
 157  *
 158  * @author Mark Reinhold
 159  * @author Mike McCloskey
 160  * @author JSR-51 Expert Group
 161  * @since 1.4
 162  */
 163 
 164 public abstract class FileChannel
 165     extends AbstractInterruptibleChannel
 166     implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel
 167 {
 168     /**
 169      * Initializes a new instance of this class.
 170      */
 171     protected FileChannel() { }
 172 
 173     /**
 174      * Opens or creates a file, returning a file channel to access the file.
 175      *
 176      * <p> The {@code options} parameter determines how the file is opened.
 177      * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE
 178      * WRITE} options determine if the file should be opened for reading and/or
 179      * writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND}
 180      * option) is contained in the array then the file is opened for reading.
 181      * By default reading or writing commences at the beginning of the file.
 182      *
 183      * <p> In the addition to {@code READ} and {@code WRITE}, the following
 184      * options may be present:
 185      *
 186      * <table class="striped">
 187      * <caption style="display:none">additional options</caption>
 188      * <thead>
 189      * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr>
 190      * </thead>
 191      * <tbody>
 192      * <tr>
 193      *   <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th>
 194      *   <td> If this option is present then the file is opened for writing and
 195      *     each invocation of the channel's {@code write} method first advances
 196      *     the position to the end of the file and then writes the requested
 197      *     data. Whether the advancement of the position and the writing of the
 198      *     data are done in a single atomic operation is system-dependent and
 199      *     therefore unspecified. The effect of {@linkplain
 200      *     #write(ByteBuffer,long) writing at a given position} with this option
 201      *     present is unspecified. This option may not be used in conjunction
 202      *     with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>
 203      * </tr>
 204      * <tr>
 205      *   <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th>
 206      *   <td> If this option is present then the existing file is truncated to
 207      *   a size of 0 bytes. This option is ignored when the file is opened only
 208      *   for reading. </td>
 209      * </tr>
 210      * <tr>
 211      *   <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th>
 212      *   <td> If this option is present then a new file is created, failing if
 213      *   the file already exists. When creating a file the check for the
 214      *   existence of the file and the creation of the file if it does not exist
 215      *   is atomic with respect to other file system operations. This option is
 216      *   ignored when the file is opened only for reading. </td>
 217      * </tr>
 218      * <tr>
 219      *   <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th>
 220      *   <td> If this option is present then an existing file is opened if it
 221      *   exists, otherwise a new file is created. When creating a file the check
 222      *   for the existence of the file and the creation of the file if it does
 223      *   not exist is atomic with respect to other file system operations. This
 224      *   option is ignored if the {@code CREATE_NEW} option is also present or
 225      *   the file is opened only for reading. </td>
 226      * </tr>
 227      * <tr>
 228      *   <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th>
 229      *   <td> When this option is present then the implementation makes a
 230      *   <em>best effort</em> attempt to delete the file when closed by
 231      *   the {@link #close close} method. If the {@code close} method is not
 232      *   invoked then a <em>best effort</em> attempt is made to delete the file
 233      *   when the Java virtual machine terminates. </td>
 234      * </tr>
 235      * <tr>
 236      *   <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th>
 237      *   <td> When creating a new file this option is a <em>hint</em> that the
 238      *   new file will be sparse. This option is ignored when not creating
 239      *   a new file. </td>
 240      * </tr>
 241      * <tr>
 242      *   <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th>
 243      *   <td> Requires that every update to the file's content or metadata be
 244      *   written synchronously to the underlying storage device. (see <a
 245      *   href="../file/package-summary.html#integrity"> Synchronized I/O file
 246      *   integrity</a>). </td>
 247      * </tr>
 248      * <tr>
 249      *   <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th>
 250      *   <td> Requires that every update to the file's content be written
 251      *   synchronously to the underlying storage device. (see <a
 252      *   href="../file/package-summary.html#integrity"> Synchronized I/O file
 253      *   integrity</a>). </td>
 254      * </tr>
 255      * </tbody>
 256      * </table>
 257      *
 258      * <p> An implementation may also support additional options.
 259      *
 260      * <p> The {@code attrs} parameter is an optional array of file {@link
 261      * FileAttribute file-attributes} to set atomically when creating the file.
 262      *
 263      * <p> The new channel is created by invoking the {@link
 264      * FileSystemProvider#newFileChannel newFileChannel} method on the
 265      * provider that created the {@code Path}.
 266      *
 267      * @param   path
 268      *          The path of the file to open or create
 269      * @param   options
 270      *          Options specifying how the file is opened
 271      * @param   attrs
 272      *          An optional list of file attributes to set atomically when
 273      *          creating the file
 274      *
 275      * @return  A new file channel
 276      *
 277      * @throws  IllegalArgumentException
 278      *          If the set contains an invalid combination of options
 279      * @throws  UnsupportedOperationException
 280      *          If the {@code path} is associated with a provider that does not
 281      *          support creating file channels, or an unsupported open option is
 282      *          specified, or the array contains an attribute that cannot be set
 283      *          atomically when creating the file
 284      * @throws  FileAlreadyExistsException
 285      *          If a file of that name already exists and the {@link
 286      *          StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified
 287      *          and the file is being opened for writing
 288      *          <i>(<a href="../file/package-summary.html#optspecex">optional
 289      *          specific exception</a>)</i>
 290      * @throws  IOException
 291      *          If an I/O error occurs
 292      * @throws  SecurityException
 293      *          If a security manager is installed and it denies an
 294      *          unspecified permission required by the implementation.
 295      *          In the case of the default provider, the {@link
 296      *          SecurityManager#checkRead(String)} method is invoked to check
 297      *          read access if the file is opened for reading. The {@link
 298      *          SecurityManager#checkWrite(String)} method is invoked to check
 299      *          write access if the file is opened for writing
 300      *
 301      * @since   1.7
 302      */
 303     public static FileChannel open(Path path,
 304                                    Set<? extends OpenOption> options,
 305                                    FileAttribute<?>... attrs)
 306         throws IOException
 307     {
 308         FileSystemProvider provider = path.getFileSystem().provider();
 309         return provider.newFileChannel(path, options, attrs);
 310     }
 311 
 312     @SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction
 313     private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
 314 
 315     /**
 316      * Opens or creates a file, returning a file channel to access the file.
 317      *
 318      * <p> An invocation of this method behaves in exactly the same way as the
 319      * invocation
 320      * {@snippet lang=java :
 321      *     // @link substring="open" target="#open(Path,Set,FileAttribute[])" :
 322      *     fc.open(file, opts, new FileAttribute<?>[0]);
 323      * }
 324      * where {@code opts} is a set of the options specified in the {@code
 325      * options} array.
 326      *
 327      * @param   path
 328      *          The path of the file to open or create
 329      * @param   options
 330      *          Options specifying how the file is opened
 331      *
 332      * @return  A new file channel
 333      *
 334      * @throws  IllegalArgumentException
 335      *          If the set contains an invalid combination of options
 336      * @throws  UnsupportedOperationException
 337      *          If the {@code path} is associated with a provider that does not
 338      *          support creating file channels, or an unsupported open option is
 339      *          specified
 340      * @throws  FileAlreadyExistsException
 341      *          If a file of that name already exists and the {@link
 342      *          StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified
 343      *          and the file is being opened for writing
 344      *          <i>(<a href="../file/package-summary.html#optspecex">optional
 345      *          specific exception</a>)</i>
 346      * @throws  IOException
 347      *          If an I/O error occurs
 348      * @throws  SecurityException
 349      *          If a security manager is installed and it denies an
 350      *          unspecified permission required by the implementation.
 351      *          In the case of the default provider, the {@link
 352      *          SecurityManager#checkRead(String)} method is invoked to check
 353      *          read access if the file is opened for reading. The {@link
 354      *          SecurityManager#checkWrite(String)} method is invoked to check
 355      *          write access if the file is opened for writing
 356      *
 357      * @since   1.7
 358      */
 359     public static FileChannel open(Path path, OpenOption... options)
 360         throws IOException
 361     {
 362         Set<OpenOption> set;
 363         if (options.length == 0) {
 364             set = Collections.emptySet();
 365         } else {
 366             set = new HashSet<>();
 367             Collections.addAll(set, options);
 368         }
 369         return open(path, set, NO_ATTRIBUTES);
 370     }
 371 
 372     // -- Channel operations --
 373 
 374     /**
 375      * Reads a sequence of bytes from this channel into the given buffer.
 376      *
 377      * <p> Bytes are read starting at this channel's current file position, and
 378      * then the file position is updated with the number of bytes actually
 379      * read.  Otherwise this method behaves exactly as specified in the {@link
 380      * ReadableByteChannel} interface. </p>
 381      *
 382      * @throws  ClosedChannelException      {@inheritDoc}
 383      * @throws  AsynchronousCloseException  {@inheritDoc}
 384      * @throws  ClosedByInterruptException  {@inheritDoc}
 385      * @throws  NonReadableChannelException {@inheritDoc}
 386      */
 387     public abstract int read(ByteBuffer dst) throws IOException;
 388 
 389     /**
 390      * Reads a sequence of bytes from this channel into a subsequence of the
 391      * given buffers.
 392      *
 393      * <p> Bytes are read starting at this channel's current file position, and
 394      * then the file position is updated with the number of bytes actually
 395      * read.  Otherwise this method behaves exactly as specified in the {@link
 396      * ScatteringByteChannel} interface.  </p>
 397      *
 398      * @throws  ClosedChannelException      {@inheritDoc}
 399      * @throws  AsynchronousCloseException  {@inheritDoc}
 400      * @throws  ClosedByInterruptException  {@inheritDoc}
 401      * @throws  NonReadableChannelException {@inheritDoc}
 402      */
 403     public abstract long read(ByteBuffer[] dsts, int offset, int length)
 404         throws IOException;
 405 
 406     /**
 407      * Reads a sequence of bytes from this channel into the given buffers.
 408      *
 409      * <p> Bytes are read starting at this channel's current file position, and
 410      * then the file position is updated with the number of bytes actually
 411      * read.  Otherwise this method behaves exactly as specified in the {@link
 412      * ScatteringByteChannel} interface.  </p>
 413      *
 414      * @throws  ClosedChannelException      {@inheritDoc}
 415      * @throws  AsynchronousCloseException  {@inheritDoc}
 416      * @throws  ClosedByInterruptException  {@inheritDoc}
 417      * @throws  NonReadableChannelException {@inheritDoc}
 418      */
 419     public final long read(ByteBuffer[] dsts) throws IOException {
 420         return read(dsts, 0, dsts.length);
 421     }
 422 
 423     /**
 424      * Writes a sequence of bytes to this channel from the given buffer.
 425      *
 426      * <p> Bytes are written starting at this channel's current file position
 427      * unless the channel is in append mode, in which case the position is
 428      * first advanced to the end of the file.  The file is grown, if necessary,
 429      * to accommodate the written bytes, and then the file position is updated
 430      * with the number of bytes actually written.  Otherwise this method
 431      * behaves exactly as specified by the {@link WritableByteChannel}
 432      * interface. </p>
 433      *
 434      * @throws  ClosedChannelException      {@inheritDoc}
 435      * @throws  AsynchronousCloseException  {@inheritDoc}
 436      * @throws  ClosedByInterruptException  {@inheritDoc}
 437      * @throws  NonWritableChannelException {@inheritDoc}
 438      */
 439     public abstract int write(ByteBuffer src) throws IOException;
 440 
 441     /**
 442      * Writes a sequence of bytes to this channel from a subsequence of the
 443      * given buffers.
 444      *
 445      * <p> Bytes are written starting at this channel's current file position
 446      * unless the channel is in append mode, in which case the position is
 447      * first advanced to the end of the file.  The file is grown, if necessary,
 448      * to accommodate the written bytes, and then the file position is updated
 449      * with the number of bytes actually written.  Otherwise this method
 450      * behaves exactly as specified in the {@link GatheringByteChannel}
 451      * interface.  </p>
 452      *
 453      * @throws  ClosedChannelException      {@inheritDoc}
 454      * @throws  AsynchronousCloseException  {@inheritDoc}
 455      * @throws  ClosedByInterruptException  {@inheritDoc}
 456      * @throws  NonWritableChannelException {@inheritDoc}
 457      */
 458     public abstract long write(ByteBuffer[] srcs, int offset, int length)
 459         throws IOException;
 460 
 461     /**
 462      * Writes a sequence of bytes to this channel from the given buffers.
 463      *
 464      * <p> Bytes are written starting at this channel's current file position
 465      * unless the channel is in append mode, in which case the position is
 466      * first advanced to the end of the file.  The file is grown, if necessary,
 467      * to accommodate the written bytes, and then the file position is updated
 468      * with the number of bytes actually written.  Otherwise this method
 469      * behaves exactly as specified in the {@link GatheringByteChannel}
 470      * interface.  </p>
 471      *
 472      * @throws  ClosedChannelException      {@inheritDoc}
 473      * @throws  AsynchronousCloseException  {@inheritDoc}
 474      * @throws  ClosedByInterruptException  {@inheritDoc}
 475      * @throws  NonWritableChannelException {@inheritDoc}
 476      */
 477     public final long write(ByteBuffer[] srcs) throws IOException {
 478         return write(srcs, 0, srcs.length);
 479     }
 480 
 481 
 482     // -- Other operations --
 483 
 484     /**
 485      * Returns this channel's file position.
 486      *
 487      * @return  This channel's file position,
 488      *          a non-negative integer counting the number of bytes
 489      *          from the beginning of the file to the current position
 490      *
 491      * @throws  ClosedChannelException
 492      *          If this channel is closed
 493      *
 494      * @throws  IOException
 495      *          If some other I/O error occurs
 496      */
 497     public abstract long position() throws IOException;
 498 
 499     /**
 500      * Sets this channel's file position.
 501      *
 502      * <p> Setting the position to a value that is greater than the file's
 503      * current size is legal but does not change the size of the file.  A later
 504      * attempt to read bytes at such a position will immediately return an
 505      * end-of-file indication.  A later attempt to write bytes at such a
 506      * position will cause the file to be grown to accommodate the new bytes;
 507      * the values of any bytes between the previous end-of-file and the
 508      * newly-written bytes are unspecified.  </p>
 509      *
 510      * @param  newPosition
 511      *         The new position, a non-negative integer counting
 512      *         the number of bytes from the beginning of the file
 513      *
 514      * @return  This file channel
 515      *
 516      * @throws  ClosedChannelException
 517      *          If this channel is closed
 518      *
 519      * @throws  IllegalArgumentException
 520      *          If the new position is negative
 521      *
 522      * @throws  IOException
 523      *          If some other I/O error occurs
 524      */
 525     public abstract FileChannel position(long newPosition) throws IOException;
 526 
 527     /**
 528      * Returns the current size of this channel's file.
 529      *
 530      * @return  The current size of this channel's file,
 531      *          measured in bytes
 532      *
 533      * @throws  ClosedChannelException
 534      *          If this channel is closed
 535      *
 536      * @throws  IOException
 537      *          If some other I/O error occurs
 538      */
 539     public abstract long size() throws IOException;
 540 
 541     /**
 542      * Truncates this channel's file to the given size.
 543      *
 544      * <p> If the given size is less than the file's current size then the file
 545      * is truncated, discarding any bytes beyond the new end of the file.  If
 546      * the given size is greater than or equal to the file's current size then
 547      * the file is not modified.  In either case, if this channel's file
 548      * position is greater than the given size then it is set to that size.
 549      * </p>
 550      *
 551      * @param  size
 552      *         The new size, a non-negative byte count
 553      *
 554      * @return  This file channel
 555      *
 556      * @throws  NonWritableChannelException
 557      *          If this channel was not opened for writing
 558      *
 559      * @throws  ClosedChannelException
 560      *          If this channel is closed
 561      *
 562      * @throws  IllegalArgumentException
 563      *          If the new size is negative
 564      *
 565      * @throws  IOException
 566      *          If some other I/O error occurs
 567      */
 568     public abstract FileChannel truncate(long size) throws IOException;
 569 
 570     /**
 571      * Forces any updates to this channel's file to be written to the storage
 572      * device that contains it.
 573      *
 574      * <p> If this channel's file resides on a local storage device then when
 575      * this method returns it is guaranteed that all changes made to the file
 576      * since this channel was created, or since this method was last invoked,
 577      * will have been written to that device.  This is useful for ensuring that
 578      * critical information is not lost in the event of a system crash.
 579      *
 580      * <p> If the file does not reside on a local device then no such guarantee
 581      * is made.
 582      *
 583      * <p> The {@code metaData} parameter can be used to limit the number of
 584      * I/O operations that this method is required to perform.  Passing
 585      * {@code false} for this parameter indicates that only updates to the
 586      * file's content need be written to storage; passing {@code true}
 587      * indicates that updates to both the file's content and metadata must be
 588      * written, which generally requires at least one more I/O operation.
 589      * Whether this parameter actually has any effect is dependent upon the
 590      * underlying operating system and is therefore unspecified.
 591      *
 592      * <p> Invoking this method may cause an I/O operation to occur even if the
 593      * channel was only opened for reading.  Some operating systems, for
 594      * example, maintain a last-access time as part of a file's metadata, and
 595      * this time is updated whenever the file is read.  Whether or not this is
 596      * actually done is system-dependent and is therefore unspecified.
 597      *
 598      * <p> This method is only guaranteed to force changes that were made to
 599      * this channel's file via the methods defined in this class, or the methods
 600      * defined by {@link java.io.FileOutputStream} or
 601      * {@link java.io.RandomAccessFile} when the channel was obtained with the
 602      * {@code getChannel} method. It may or may not force changes that were made
 603      * by modifying the content of a
 604      * {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by
 605      * invoking the {@link #map map} method.  Invoking the {@link
 606      * MappedByteBuffer#force force} method of the mapped byte buffer will
 607      * force changes made to the buffer's content to be written.  </p>
 608      *
 609      * @param   metaData
 610      *          If {@code true} then this method is required to force changes
 611      *          to both the file's content and metadata to be written to
 612      *          storage; otherwise, it need only force content changes to be
 613      *          written
 614      *
 615      * @throws  ClosedChannelException
 616      *          If this channel is closed
 617      *
 618      * @throws  IOException
 619      *          If some other I/O error occurs
 620      */
 621     public abstract void force(boolean metaData) throws IOException;
 622 
 623     /**
 624      * Transfers bytes from this channel's file to the given writable byte
 625      * channel.
 626      *
 627      * <p> An attempt is made to read up to {@code count} bytes starting at
 628      * the given {@code position} in this channel's file and write them to the
 629      * target channel.  An invocation of this method may or may not transfer
 630      * all of the requested bytes; whether or not it does so depends upon the
 631      * natures and states of the channels.  Fewer than the requested number of
 632      * bytes are transferred if this channel's file contains fewer than
 633      * {@code count} bytes starting at the given {@code position}, or if the
 634      * target channel is non-blocking and it has fewer than {@code count}
 635      * bytes free in its output buffer.
 636      *
 637      * <p> This method does not modify this channel's position.  If the given
 638      * position is greater than or equal to the file's current size then no
 639      * bytes are transferred.  If the target channel has a position then bytes
 640      * are written starting at that position and then the position
 641      * is incremented by the number of bytes written.
 642      *
 643      * <p> This method is potentially much more efficient than a simple loop
 644      * that reads from this channel and writes to the target channel.  Many
 645      * operating systems can transfer bytes directly from the filesystem cache
 646      * to the target channel without actually copying them.  </p>
 647      *
 648      * @param  position
 649      *         The position within the file at which the transfer is to begin;
 650      *         must be non-negative
 651      *
 652      * @param  count
 653      *         The maximum number of bytes to be transferred; must be
 654      *         non-negative
 655      *
 656      * @param  target
 657      *         The target channel
 658      *
 659      * @return  The number of bytes, possibly zero,
 660      *          that were actually transferred
 661      *
 662      * @throws IllegalArgumentException
 663      *         If the preconditions on the parameters do not hold
 664      *
 665      * @throws  NonReadableChannelException
 666      *          If this channel was not opened for reading
 667      *
 668      * @throws  NonWritableChannelException
 669      *          If the target channel was not opened for writing
 670      *
 671      * @throws  ClosedChannelException
 672      *          If either this channel or the target channel is closed
 673      *
 674      * @throws  AsynchronousCloseException
 675      *          If another thread closes either channel
 676      *          while the transfer is in progress
 677      *
 678      * @throws  ClosedByInterruptException
 679      *          If another thread interrupts the current thread while the
 680      *          transfer is in progress, thereby closing both channels and
 681      *          setting the current thread's interrupt status
 682      *
 683      * @throws  IOException
 684      *          If some other I/O error occurs
 685      */
 686     public abstract long transferTo(long position, long count,
 687                                     WritableByteChannel target)
 688         throws IOException;
 689 
 690     /**
 691      * Transfers bytes into this channel's file from the given readable byte
 692      * channel.
 693      *
 694      * <p> An attempt is made to read up to {@code count} bytes from the
 695      * source channel and write them to this channel's file starting at the
 696      * given {@code position}.  An invocation of this method may or may not
 697      * transfer all of the requested bytes; whether or not it does so depends
 698      * upon the natures and states of the channels.  Fewer than the requested
 699      * number of bytes will be transferred if the source channel has fewer than
 700      * {@code count} bytes remaining, or if the source channel is non-blocking
 701      * and has fewer than {@code count} bytes immediately available in its
 702      * input buffer. No bytes are transferred, and zero is returned, if the
 703      * source has reached end-of-stream.
 704      *
 705      * <p> This method does not modify this channel's position.  If the given
 706      * position is greater than or equal to the file's current size then the
 707      * file will be grown to accommodate the new bytes; the values of any bytes
 708      * between the previous end-of-file and the newly-written bytes are
 709      * unspecified.  If the source channel has a position then bytes are read
 710      * starting at that position and then the position is incremented by the
 711      * number of bytes read.
 712      *
 713      * <p> This method is potentially much more efficient than a simple loop
 714      * that reads from the source channel and writes to this channel.  Many
 715      * operating systems can transfer bytes directly from the source channel
 716      * into the filesystem cache without actually copying them.  </p>
 717      *
 718      * @param  src
 719      *         The source channel
 720      *
 721      * @param  position
 722      *         The file position at which the transfer is to begin;
 723      *         must be non-negative
 724      *
 725      * @param  count
 726      *         The maximum number of bytes to be transferred; must be
 727      *         non-negative
 728      *
 729      * @return  The number of bytes, possibly zero,
 730      *          that were actually transferred
 731      *
 732      * @throws IllegalArgumentException
 733      *         If the preconditions on the parameters do not hold
 734      *
 735      * @throws  NonReadableChannelException
 736      *          If the source channel was not opened for reading
 737      *
 738      * @throws  NonWritableChannelException
 739      *          If this channel was not opened for writing
 740      *
 741      * @throws  ClosedChannelException
 742      *          If either this channel or the source channel is closed
 743      *
 744      * @throws  AsynchronousCloseException
 745      *          If another thread closes either channel
 746      *          while the transfer is in progress
 747      *
 748      * @throws  ClosedByInterruptException
 749      *          If another thread interrupts the current thread while the
 750      *          transfer is in progress, thereby closing both channels and
 751      *          setting the current thread's interrupt status
 752      *
 753      * @throws  IOException
 754      *          If some other I/O error occurs
 755      */
 756     public abstract long transferFrom(ReadableByteChannel src,
 757                                       long position, long count)
 758         throws IOException;
 759 
 760     /**
 761      * Reads a sequence of bytes from this channel into the given buffer,
 762      * starting at the given file position.
 763      *
 764      * <p> This method works in the same manner as the {@link
 765      * #read(ByteBuffer)} method, except that bytes are read starting at the
 766      * given file position rather than at the channel's current position.  This
 767      * method does not modify this channel's position.  If the given position
 768      * is greater than or equal to the file's current size then no bytes are
 769      * read.  </p>
 770      *
 771      * @param  dst
 772      *         The buffer into which bytes are to be transferred
 773      *
 774      * @param  position
 775      *         The file position at which the transfer is to begin;
 776      *         must be non-negative
 777      *
 778      * @return  The number of bytes read, possibly zero, or {@code -1} if the
 779      *          given position is greater than or equal to the file's current
 780      *          size
 781      *
 782      * @throws  IllegalArgumentException
 783      *          If the position is negative or the buffer is read-only
 784      *
 785      * @throws  NonReadableChannelException
 786      *          If this channel was not opened for reading
 787      *
 788      * @throws  ClosedChannelException
 789      *          If this channel is closed
 790      *
 791      * @throws  AsynchronousCloseException
 792      *          If another thread closes this channel
 793      *          while the read operation is in progress
 794      *
 795      * @throws  ClosedByInterruptException
 796      *          If another thread interrupts the current thread
 797      *          while the read operation is in progress, thereby
 798      *          closing the channel and setting the current thread's
 799      *          interrupt status
 800      *
 801      * @throws  IOException
 802      *          If some other I/O error occurs
 803      */
 804     public abstract int read(ByteBuffer dst, long position) throws IOException;
 805 
 806     /**
 807      * Writes a sequence of bytes to this channel from the given buffer,
 808      * starting at the given file position.
 809      *
 810      * <p> This method works in the same manner as the {@link
 811      * #write(ByteBuffer)} method, except that bytes are written starting at
 812      * the given file position rather than at the channel's current position.
 813      * This method does not modify this channel's position.  If the given
 814      * position is greater than or equal to the file's current size then the
 815      * file will be grown to accommodate the new bytes; the values of any bytes
 816      * between the previous end-of-file and the newly-written bytes are
 817      * unspecified.  </p>
 818      *
 819      * <p> If the file is open in <a href="#append-mode">append mode</a>, then
 820      * the effect of invoking this method is unspecified.
 821      *
 822      * @param  src
 823      *         The buffer from which bytes are to be transferred
 824      *
 825      * @param  position
 826      *         The file position at which the transfer is to begin;
 827      *         must be non-negative
 828      *
 829      * @return  The number of bytes written, possibly zero
 830      *
 831      * @throws  IllegalArgumentException
 832      *          If the position is negative
 833      *
 834      * @throws  NonWritableChannelException
 835      *          If this channel was not opened for writing
 836      *
 837      * @throws  ClosedChannelException
 838      *          If this channel is closed
 839      *
 840      * @throws  AsynchronousCloseException
 841      *          If another thread closes this channel
 842      *          while the write operation is in progress
 843      *
 844      * @throws  ClosedByInterruptException
 845      *          If another thread interrupts the current thread
 846      *          while the write operation is in progress, thereby
 847      *          closing the channel and setting the current thread's
 848      *          interrupt status
 849      *
 850      * @throws  IOException
 851      *          If some other I/O error occurs
 852      */
 853     public abstract int write(ByteBuffer src, long position) throws IOException;
 854 
 855 
 856     // -- Memory-mapped buffers --
 857 
 858     /**
 859      * A file-mapping mode.
 860      *
 861      * @since 1.4
 862      *
 863      * @see java.nio.channels.FileChannel#map
 864      */
 865     public static class MapMode {
 866 
 867         /**
 868          * Mode for a read-only mapping.
 869          */
 870         public static final MapMode READ_ONLY
 871             = new MapMode("READ_ONLY");
 872 
 873         /**
 874          * Mode for a read/write mapping.
 875          */
 876         public static final MapMode READ_WRITE
 877             = new MapMode("READ_WRITE");
 878 
 879         /**
 880          * Mode for a private (copy-on-write) mapping.
 881          */
 882         public static final MapMode PRIVATE
 883             = new MapMode("PRIVATE");
 884 
 885         private final String name;
 886 
 887         /**
 888          * Constructs an instance of this class. This constructor may be used
 889          * by code in java.base to create file mapping modes beyond the file
 890          * mapping modes defined here.
 891          * @param name the name of the map mode
 892          */
 893         private MapMode(String name) {
 894             this.name = name;
 895         }
 896 
 897         /**
 898          * Returns a string describing this file-mapping mode.
 899          *
 900          * @return  A descriptive string
 901          */
 902         public String toString() {
 903             return name;
 904         }
 905 
 906     }
 907 
 908     /**
 909      * Maps a region of this channel's file directly into memory.
 910      *
 911      * <p> The {@code mode} parameter specifies how the region of the file is
 912      * mapped and may be one of the following modes:
 913      *
 914      * <ul>
 915      *
 916      *   <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer
 917      *   will cause a {@link java.nio.ReadOnlyBufferException} to be thrown.
 918      *   ({@link MapMode#READ_ONLY MapMode.READ_ONLY}) </p></li>
 919      *
 920      *   <li><p> <i>Read/write:</i> Changes made to the resulting buffer will
 921      *   eventually be propagated to the file; they may or may not be made
 922      *   visible to other programs that have mapped the same file.  ({@link
 923      *   MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li>
 924      *
 925      *   <li><p> <i>Private:</i> Changes made to the resulting buffer will not
 926      *   be propagated to the file and will not be visible to other programs
 927      *   that have mapped the same file; instead, they will cause private
 928      *   copies of the modified portions of the buffer to be created.  ({@link
 929      *   MapMode#PRIVATE MapMode.PRIVATE}) </p></li>
 930      *
 931      * </ul>
 932      *
 933      * <p> An implementation may support additional map modes.
 934      *
 935      * <p> For a read-only mapping, this channel must have been opened for
 936      * reading; for a read/write or private mapping, this channel must have
 937      * been opened for both reading and writing.
 938      *
 939      * <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>}
 940      * returned by this method will have a position of zero and a limit and
 941      * capacity of {@code size}; its mark will be undefined.  The buffer and
 942      * the mapping that it represents will remain valid until the buffer itself
 943      * is garbage-collected.
 944      *
 945      * <p> A mapping, once established, is not dependent upon the file channel
 946      * that was used to create it.  Closing the channel, in particular, has no
 947      * effect upon the validity of the mapping.
 948      *
 949      * <p> Many of the details of memory-mapped files are inherently dependent
 950      * upon the underlying operating system and are therefore unspecified.  The
 951      * behavior of this method when the requested region is not completely
 952      * contained within this channel's file is unspecified.  Whether changes
 953      * made to the content or size of the underlying file, by this program or
 954      * another, are propagated to the buffer is unspecified.  The rate at which
 955      * changes to the buffer are propagated to the file is unspecified.
 956      *
 957      * <p> For most operating systems, mapping a file into memory is more
 958      * expensive than reading or writing a few tens of kilobytes of data via
 959      * the usual {@link #read read} and {@link #write write} methods.  From the
 960      * standpoint of performance it is generally only worth mapping relatively
 961      * large files into memory.  </p>
 962      *
 963      * @param  mode
 964      *         One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link
 965      *         MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE
 966      *         PRIVATE} defined in the {@link MapMode} class, according to
 967      *         whether the file is to be mapped read-only, read/write, or
 968      *         privately (copy-on-write), respectively, or an implementation
 969      *         specific map mode
 970      *
 971      * @param  position
 972      *         The position within the file at which the mapped region
 973      *         is to start; must be non-negative
 974      *
 975      * @param  size
 976      *         The size of the region to be mapped; must be non-negative and
 977      *         no greater than {@link java.lang.Integer#MAX_VALUE}
 978      *
 979      * @return The mapped byte buffer
 980      *
 981      * @throws NonReadableChannelException
 982      *         If the {@code mode} is {@link MapMode#READ_ONLY READ_ONLY} or
 983      *         an implementation specific map mode requiring read access,
 984      *         but this channel was not opened for reading
 985      *
 986      * @throws NonWritableChannelException
 987      *         If the {@code mode} is {@link MapMode#READ_WRITE READ_WRITE},
 988      *         {@link MapMode#PRIVATE PRIVATE} or an implementation specific
 989      *         map mode requiring write access, but this channel was not
 990      *         opened for both reading and writing
 991      *
 992      * @throws IllegalArgumentException
 993      *         If the preconditions on the parameters do not hold
 994      *
 995      * @throws UnsupportedOperationException
 996      *         If an unsupported map mode is specified
 997      *
 998      * @throws IOException
 999      *         If some other I/O error occurs
1000      *
1001      * @see java.nio.channels.FileChannel.MapMode
1002      * @see java.nio.MappedByteBuffer
1003      */
1004     public abstract MappedByteBuffer map(MapMode mode, long position, long size)
1005         throws IOException;
1006 
1007     /**
1008      * Maps a region of this channel's file into a new mapped memory segment,
1009      * with the given offset, size and arena.
1010      * The {@linkplain MemorySegment#address() address} of the returned memory
1011      * segment is the starting address of the mapped off-heap region backing
1012      * the segment.
1013      * <p>
1014      * The lifetime of the returned segment is controlled by the provided arena.
1015      * For instance, if the provided arena is a closeable arena,
1016      * the returned segment will be unmapped when the provided closeable arena
1017      * is {@linkplain Arena#close() closed}.
1018      * <p> If the specified mapping mode is
1019      * {@linkplain FileChannel.MapMode#READ_ONLY READ_ONLY}, the resulting
1020      * segment will be read-only (see {@link MemorySegment#isReadOnly()}).
1021      *
1022      * <p> The content of a mapped memory segment can change at any time, for
1023      * example if the content of the corresponding region of the mapped file is
1024      * changed by this (or another) program.  Whether such changes occur, and
1025      * when they occur, is operating-system dependent and therefore unspecified.
1026      *
1027      * <p> All or part of a mapped memory segment may become inaccessible at any
1028      * time, for example if the backing mapped file is truncated. An attempt to
1029      * access an inaccessible region of a mapped memory segment will not change
1030      * the segment's content and will cause an unspecified exception to be
1031      * thrown either at the time of the access or at some later time. It is
1032      * therefore strongly recommended that appropriate precautions be taken to
1033      * avoid the manipulation of a mapped file by this (or another) program,
1034      * except to read or write the file's content.
1035      *
1036      * @implNote When obtaining a mapped segment from a newly created file
1037      *           channel, the initialization state of the contents of the block
1038      *           of mapped memory associated with the returned mapped memory
1039      *           segment is unspecified and should not be relied upon.
1040      *
1041      * @implSpec The default implementation of this method throws
1042      *           {@code UnsupportedOperationException}.
1043      *
1044      * @param   mode
1045      *          The file mapping mode, see
1046      *          {@link FileChannel#map(FileChannel.MapMode, long, long)};
1047      *          the mapping mode might affect the behavior of the returned
1048      *          memory mapped segment (see {@link MemorySegment#force()}).
1049      *
1050      * @param   offset
1051      *          The offset (expressed in bytes) within the file at which the
1052      *          mapped segment is to start.
1053      *
1054      * @param   size
1055      *          The size (in bytes) of the mapped memory backing the memory
1056      *          segment.
1057      *
1058      * @param   arena
1059      *          The segment arena.
1060      *
1061      * @return  A new mapped memory segment.
1062      *
1063      * @throws  IllegalArgumentException
1064      *          If {@code offset < 0}, {@code size < 0} or
1065      *          {@code offset + size} overflows the range of {@code long}.
1066      *
1067      * @throws  IllegalStateException
1068      *          If {@code arena.isAlive() == false}.
1069      *
1070      * @throws  WrongThreadException
1071      *          If {@code arena} is a confined scoped arena, and this method is called from a
1072      *          thread {@code T}, other than the scoped arena's owner thread.
1073      *
1074      * @throws  NonReadableChannelException
1075      *          If the {@code mode} is {@link MapMode#READ_ONLY READ_ONLY} or
1076      *          an implementation specific map mode requiring read access,
1077      *          but this channel was not opened for reading.
1078      *
1079      * @throws  NonWritableChannelException
1080      *          If the {@code mode} is {@link MapMode#READ_WRITE READ_WRITE},
1081      *          {@link MapMode#PRIVATE PRIVATE} or an implementation specific
1082      *          map mode requiring write access, but this channel was not
1083      *          opened for both reading and writing.
1084      *
1085      * @throws  IOException
1086      *          If some other I/O error occurs.
1087      *
1088      * @throws  UnsupportedOperationException
1089      *          If an unsupported map mode is specified.
1090      *
1091      * @since   22
1092      */
1093     public MemorySegment map(MapMode mode, long offset, long size, Arena arena)
1094         throws IOException
1095     {
1096         throw new UnsupportedOperationException();
1097     }
1098 
1099     // -- Locks --
1100 
1101     /**
1102      * Acquires a lock on the given region of this channel's file.
1103      *
1104      * <p> An invocation of this method will block until the region can be
1105      * locked, this channel is closed, or the invoking thread is interrupted,
1106      * whichever comes first.
1107      *
1108      * <p> If this channel is closed by another thread during an invocation of
1109      * this method then an {@link AsynchronousCloseException} will be thrown.
1110      *
1111      * <p> If the invoking thread is interrupted while waiting to acquire the
1112      * lock then its interrupt status will be set and a {@link
1113      * FileLockInterruptionException} will be thrown.  If the invoker's
1114      * interrupt status is set when this method is invoked then that exception
1115      * will be thrown immediately; the thread's interrupt status will not be
1116      * changed.
1117      *
1118      * <p> The region specified by the {@code position} and {@code size}
1119      * parameters need not be contained within, or even overlap, the actual
1120      * underlying file.  Lock regions are fixed in size; if a locked region
1121      * initially contains the end of the file and the file grows beyond the
1122      * region then the new portion of the file will not be covered by the lock.
1123      * If a file is expected to grow in size and a lock on the entire file is
1124      * required then a region starting at zero, and no smaller than the
1125      * expected maximum size of the file, should be locked.  The zero-argument
1126      * {@link #lock()} method simply locks a region of size {@link
1127      * Long#MAX_VALUE}.  If the {@code position} is non-negative and the
1128      * {@code size} is zero, then a lock of size
1129      * {@code Long.MAX_VALUE - position} is returned.
1130      *
1131      * <p> Some operating systems do not support shared locks, in which case a
1132      * request for a shared lock is automatically converted into a request for
1133      * an exclusive lock.  Whether the newly-acquired lock is shared or
1134      * exclusive may be tested by invoking the resulting lock object's {@link
1135      * FileLock#isShared() isShared} method.
1136      *
1137      * <p> File locks are held on behalf of the entire Java virtual machine.
1138      * They are not suitable for controlling access to a file by multiple
1139      * threads within the same virtual machine.  </p>
1140      *
1141      * @param  position
1142      *         The position at which the locked region is to start; must be
1143      *         non-negative
1144      *
1145      * @param  size
1146      *         The size of the locked region; must be non-negative, and the sum
1147      *         {@code position}&nbsp;+&nbsp;{@code size} must be non-negative.
1148      *         A value of zero means to lock all bytes from the specified
1149      *         starting position to the end of the file, regardless of whether
1150      *         the file is subsequently extended or truncated
1151      *
1152      * @param  shared
1153      *         {@code true} to request a shared lock, in which case this
1154      *         channel must be open for reading (and possibly writing);
1155      *         {@code false} to request an exclusive lock, in which case this
1156      *         channel must be open for writing (and possibly reading)
1157      *
1158      * @return  A lock object representing the newly-acquired lock
1159      *
1160      * @throws  IllegalArgumentException
1161      *          If the preconditions on the parameters do not hold
1162      *
1163      * @throws  ClosedChannelException
1164      *          If this channel is closed
1165      *
1166      * @throws  AsynchronousCloseException
1167      *          If another thread closes this channel while the invoking
1168      *          thread is blocked in this method
1169      *
1170      * @throws  FileLockInterruptionException
1171      *          If the invoking thread is interrupted while blocked in this
1172      *          method
1173      *
1174      * @throws  OverlappingFileLockException
1175      *          If a lock that overlaps the requested region is already held by
1176      *          this Java virtual machine, or if another thread is already
1177      *          blocked in this method and is attempting to lock an overlapping
1178      *          region
1179      *
1180      * @throws  NonReadableChannelException
1181      *          If {@code shared} is {@code true} but this channel was not
1182      *          opened for reading
1183      *
1184      * @throws  NonWritableChannelException
1185      *          If {@code shared} is {@code false} but this channel was not
1186      *          opened for writing
1187      *
1188      * @throws  IOException
1189      *          If some other I/O error occurs
1190      *
1191      * @see     #lock()
1192      * @see     #tryLock()
1193      * @see     #tryLock(long,long,boolean)
1194      */
1195     public abstract FileLock lock(long position, long size, boolean shared)
1196         throws IOException;
1197 
1198     /**
1199      * Acquires an exclusive lock on this channel's file.
1200      *
1201      * <p> An invocation of this method of the form {@code fc.lock()} behaves
1202      * in exactly the same way as the invocation
1203      *
1204      * {@snippet lang=java :
1205      *     // @link substring="lock" target="#lock(long,long,boolean)" :
1206      *     fc.lock(0L, Long.MAX_VALUE, false)
1207      * }
1208      *
1209      * @return  A lock object representing the newly-acquired lock
1210      *
1211      * @throws  ClosedChannelException
1212      *          If this channel is closed
1213      *
1214      * @throws  AsynchronousCloseException
1215      *          If another thread closes this channel while the invoking
1216      *          thread is blocked in this method
1217      *
1218      * @throws  FileLockInterruptionException
1219      *          If the invoking thread is interrupted while blocked in this
1220      *          method
1221      *
1222      * @throws  OverlappingFileLockException
1223      *          If a lock that overlaps the requested region is already held by
1224      *          this Java virtual machine, or if another thread is already
1225      *          blocked in this method and is attempting to lock an overlapping
1226      *          region of the same file
1227      *
1228      * @throws  NonWritableChannelException
1229      *          If this channel was not opened for writing
1230      *
1231      * @throws  IOException
1232      *          If some other I/O error occurs
1233      *
1234      * @see     #lock(long,long,boolean)
1235      * @see     #tryLock()
1236      * @see     #tryLock(long,long,boolean)
1237      */
1238     public final FileLock lock() throws IOException {
1239         return lock(0L, Long.MAX_VALUE, false);
1240     }
1241 
1242     /**
1243      * Attempts to acquire a lock on the given region of this channel's file.
1244      *
1245      * <p> This method does not block.  An invocation always returns
1246      * immediately, either having acquired a lock on the requested region or
1247      * having failed to do so.  If it fails to acquire a lock because an
1248      * overlapping lock is held by another program then it returns
1249      * {@code null}.  If it fails to acquire a lock for any other reason then
1250      * an appropriate exception is thrown.
1251      *
1252      * <p> The region specified by the {@code position} and {@code size}
1253      * parameters need not be contained within, or even overlap, the actual
1254      * underlying file.  Lock regions are fixed in size; if a locked region
1255      * initially contains the end of the file and the file grows beyond the
1256      * region then the new portion of the file will not be covered by the lock.
1257      * If a file is expected to grow in size and a lock on the entire file is
1258      * required then a region starting at zero, and no smaller than the
1259      * expected maximum size of the file, should be locked.  The zero-argument
1260      * {@link #tryLock()} method simply locks a region of size {@link
1261      * Long#MAX_VALUE}.  If the {@code position} is non-negative and the
1262      * {@code size} is zero, then a lock of size
1263      * {@code Long.MAX_VALUE - position} is returned.
1264      *
1265      * <p> Some operating systems do not support shared locks, in which case a
1266      * request for a shared lock is automatically converted into a request for
1267      * an exclusive lock.  Whether the newly-acquired lock is shared or
1268      * exclusive may be tested by invoking the resulting lock object's {@link
1269      * FileLock#isShared() isShared} method.
1270      *
1271      * <p> File locks are held on behalf of the entire Java virtual machine.
1272      * They are not suitable for controlling access to a file by multiple
1273      * threads within the same virtual machine.  </p>
1274      *
1275      * @param  position
1276      *         The position at which the locked region is to start; must be
1277      *         non-negative
1278      *
1279      * @param  size
1280      *         The size of the locked region; must be non-negative, and the sum
1281      *         {@code position}&nbsp;+&nbsp;{@code size} must be non-negative.
1282      *         A value of zero means to lock all bytes from the specified
1283      *         starting position to the end of the file, regardless of whether
1284      *         the file is subsequently extended or truncated
1285      *
1286      * @param  shared
1287      *         {@code true} to request a shared lock,
1288      *         {@code false} to request an exclusive lock
1289      *
1290      * @return  A lock object representing the newly-acquired lock,
1291      *          or {@code null} if the lock could not be acquired
1292      *          because another program holds an overlapping lock
1293      *
1294      * @throws  IllegalArgumentException
1295      *          If the preconditions on the parameters do not hold
1296      *
1297      * @throws  ClosedChannelException
1298      *          If this channel is closed
1299      *
1300      * @throws  OverlappingFileLockException
1301      *          If a lock that overlaps the requested region is already held by
1302      *          this Java virtual machine, or if another thread is already
1303      *          blocked in this method and is attempting to lock an overlapping
1304      *          region of the same file
1305      *
1306      * @throws  NonReadableChannelException
1307      *          If {@code shared} is {@code true} but this channel was not
1308      *          opened for reading
1309      *
1310      * @throws  NonWritableChannelException
1311      *          If {@code shared} is {@code false} but this channel was not
1312      *          opened for writing
1313      *
1314      * @throws  IOException
1315      *          If some other I/O error occurs
1316      *
1317      * @see     #lock()
1318      * @see     #lock(long,long,boolean)
1319      * @see     #tryLock()
1320      */
1321     public abstract FileLock tryLock(long position, long size, boolean shared)
1322         throws IOException;
1323 
1324     /**
1325      * Attempts to acquire an exclusive lock on this channel's file.
1326      *
1327      * <p> An invocation of this method of the form {@code fc.tryLock()}
1328      * behaves in exactly the same way as the invocation
1329      *
1330      * {@snippet lang=java :
1331      *     // @link substring="tryLock" target="#tryLock(long,long,boolean)" :
1332      *     fc.tryLock(0L, Long.MAX_VALUE, false)
1333      * }
1334      *
1335      * @return  A lock object representing the newly-acquired lock,
1336      *          or {@code null} if the lock could not be acquired
1337      *          because another program holds an overlapping lock
1338      *
1339      * @throws  ClosedChannelException
1340      *          If this channel is closed
1341      *
1342      * @throws  OverlappingFileLockException
1343      *          If a lock that overlaps the requested region is already held by
1344      *          this Java virtual machine, or if another thread is already
1345      *          blocked in this method and is attempting to lock an overlapping
1346      *          region
1347      *
1348      * @throws  NonWritableChannelException
1349      *          If this channel was not opened for writing
1350      *
1351      * @throws  IOException
1352      *          If some other I/O error occurs
1353      *
1354      * @see     #lock()
1355      * @see     #lock(long,long,boolean)
1356      * @see     #tryLock(long,long,boolean)
1357      */
1358     public final FileLock tryLock() throws IOException {
1359         return tryLock(0L, Long.MAX_VALUE, false);
1360     }
1361 
1362 }