1 /*
   2  * Copyright (c) 2007, 2009, 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.nio.file.*;
  29 import java.nio.file.attribute.FileAttribute;
  30 import java.nio.file.spi.*;
  31 import java.nio.ByteBuffer;
  32 import java.io.IOException;
  33 import java.util.concurrent.Future;
  34 import java.util.concurrent.ExecutorService;
  35 import java.util.Set;
  36 import java.util.HashSet;
  37 import java.util.Collections;
  38 
  39 /**
  40  * An asynchronous channel for reading, writing, and manipulating a file.
  41  *
  42  * <p> An asynchronous file channel is created when a file is opened by invoking
  43  * one of the {@link #open open} methods defined by this class. The file contains
  44  * a variable-length sequence of bytes that can be read and written and whose
  45  * current size can be {@link #size() queried}. The size of the file increases
  46  * when bytes are written beyond its  current size; the size of the file decreases
  47  * when it is {@link #truncate truncated}.
  48  *
  49  * <p> An asynchronous file channel does not have a <i>current position</i>
  50  * within the file. Instead, the file position is specified to each read and
  51  * write method that initiates asynchronous operations. A {@link CompletionHandler}
  52  * is specified as a parameter and is invoked to consume the result of the I/O
  53  * operation. This class also defines read and write methods that initiate
  54  * asynchronous operations, returning a {@link Future} to represent the pending
  55  * result of the operation. The {@code Future} may be used to check if the
  56  * operation has completed, wait for its completion, and retrieve the result.
  57  *
  58  * <p> In addition to read and write operations, this class defines the
  59  * following operations: </p>
  60  *
  61  * <ul>
  62  *
  63  *   <li><p> Updates made to a file may be {@link #force <i>forced
  64  *   out</i>} to the underlying storage device, ensuring that data are not
  65  *   lost in the event of a system crash.  </p></li>
  66  *
  67  *   <li><p> A region of a file may be {@link #lock <i>locked</i>} against
  68  *   access by other programs.  </p></li>
  69  *
  70  * </ul>
  71  *
  72  * <p> An {@code AsynchronousFileChannel} is associated with a thread pool to
  73  * which tasks are submitted to handle I/O events and dispatch to completion
  74  * handlers that consume the results of I/O operations on the channel. The
  75  * completion handler for an I/O operation initiated on a channel is guaranteed
  76  * to be invoked by one of the threads in the thread pool (This ensures that the
  77  * completion handler is run by a thread with the expected <em>identity</em>).
  78  * Where an I/O operation completes immediately, and the initiating thread is
  79  * itself a thread in the thread pool, then the completion handler may be invoked
  80  * directly by the initiating thread. When an {@code AsynchronousFileChannel} is
  81  * created without specifying a thread pool then the channel is associated with
  82  * a system-dependent default thread pool that may be shared with other
  83  * channels. The default thread pool is configured by the system properties
  84  * defined by the {@link AsynchronousChannelGroup} class.
  85  *
  86  * <p> Channels of this type are safe for use by multiple concurrent threads. The
  87  * {@link Channel#close close} method may be invoked at any time, as specified
  88  * by the {@link Channel} interface. This causes all outstanding asynchronous
  89  * operations on the channel to complete with the exception {@link
  90  * AsynchronousCloseException}. Multiple read and write operations may be
  91  * outstanding at the same time. When multiple read and write operations are
  92  * outstanding then the ordering of the I/O operations, and the order that the
  93  * completion handlers are invoked, is not specified; they are not, in particular,
  94  * guaranteed to execute in the order that the operations were initiated. The
  95  * {@link java.nio.ByteBuffer ByteBuffers} used when reading or writing are not
  96  * safe for use by multiple concurrent I/O operations. Furthermore, after an I/O
  97  * operation is initiated then care should be taken to ensure that the buffer is
  98  * not accessed until after the operation has completed.
  99  *
 100  * <p> As with {@link FileChannel}, the view of a file provided by an instance of
 101  * this class is guaranteed to be consistent with other views of the same file
 102  * provided by other instances in the same program.  The view provided by an
 103  * instance of this class may or may not, however, be consistent with the views
 104  * seen by other concurrently-running programs due to caching performed by the
 105  * underlying operating system and delays induced by network-filesystem protocols.
 106  * This 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  * @since 1.7
 112  */
 113 
 114 public abstract class AsynchronousFileChannel
 115     implements AsynchronousChannel
 116 {
 117     /**
 118      * Initializes a new instance of this class.
 119      */
 120     protected AsynchronousFileChannel() {
 121     }
 122 
 123     /**
 124      * Opens or creates a file for reading and/or writing, returning an
 125      * asynchronous file channel to access the file.
 126      *
 127      * <p> The {@code options} parameter determines how the file is opened.
 128      * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE
 129      * WRITE} options determines if the file should be opened for reading and/or
 130      * writing. If neither option is contained in the array then an existing file
 131      * is opened for  reading.
 132      *
 133      * <p> In addition to {@code READ} and {@code WRITE}, the following options
 134      * may be present:
 135      *
 136      * <table border=1 cellpadding=5 summary="">
 137      * <tr> <th>Option</th> <th>Description</th> </tr>
 138      * <tr>
 139      *   <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td>
 140      *   <td> When opening an existing file, the file is first truncated to a
 141      *   size of 0 bytes. This option is ignored when the file is opened only
 142      *   for reading.</td>
 143      * </tr>
 144      * <tr>
 145      *   <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td>
 146      *   <td> If this option is present then a new file is created, failing if
 147      *   the file already exists. When creating a file the check for the
 148      *   existence of the file and the creation of the file if it does not exist
 149      *   is atomic with respect to other file system operations. This option is
 150      *   ignored when the file is opened only for reading. </td>
 151      * </tr>
 152      * <tr>
 153      *   <td > {@link StandardOpenOption#CREATE CREATE} </td>
 154      *   <td> If this option is present then an existing file is opened if it
 155      *   exists, otherwise a new file is created. When creating a file the check
 156      *   for the existence of the file and the creation of the file if it does
 157      *   not exist is atomic with respect to other file system operations. This
 158      *   option is ignored if the {@code CREATE_NEW} option is also present or
 159      *   the file is opened only for reading. </td>
 160      * </tr>
 161      * <tr>
 162      *   <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td>
 163      *   <td> When this option is present then the implementation makes a
 164      *   <em>best effort</em> attempt to delete the file when closed by the
 165      *   the {@link #close close} method. If the {@code close} method is not
 166      *   invoked then a <em>best effort</em> attempt is made to delete the file
 167      *   when the Java virtual machine terminates. </td>
 168      * </tr>
 169      * <tr>
 170      *   <td>{@link StandardOpenOption#SPARSE SPARSE} </td>
 171      *   <td> When creating a new file this option is a <em>hint</em> that the
 172      *   new file will be sparse. This option is ignored when not creating
 173      *   a new file. </td>
 174      * </tr>
 175      * <tr>
 176      *   <td> {@link StandardOpenOption#SYNC SYNC} </td>
 177      *   <td> Requires that every update to the file's content or metadata be
 178      *   written synchronously to the underlying storage device. (see <a
 179      *   href="../file/package-summary.html#integrity"> Synchronized I/O file
 180      *   integrity</a>). </td>
 181      * <tr>
 182      * <tr>
 183      *   <td> {@link StandardOpenOption#DSYNC DSYNC} </td>
 184      *   <td> Requires that every update to the file's content be written
 185      *   synchronously to the underlying storage device. (see <a
 186      *   href="../file/package-summary.html#integrity"> Synchronized I/O file
 187      *   integrity</a>). </td>
 188      * </tr>
 189      * </table>
 190      *
 191      * <p> An implementation may also support additional options.
 192      *
 193      * <p> The {@code executor} parameter is the {@link ExecutorService} to
 194      * which tasks are submitted to handle I/O events and dispatch completion
 195      * results for operations initiated on resulting channel.
 196      * The nature of these tasks is highly implementation specific and so care
 197      * should be taken when configuring the {@code Executor}. Minimally it
 198      * should support an unbounded work queue and should not run tasks on the
 199      * caller thread of the {@link ExecutorService#execute execute} method.
 200      * Shutting down the executor service while the channel is open results in
 201      * unspecified behavior.
 202      *
 203      * <p> The {@code attrs} parameter is an optional array of file {@link
 204      * FileAttribute file-attributes} to set atomically when creating the file.
 205      *
 206      * <p> The new channel is created by invoking the {@link
 207      * FileSystemProvider#newFileChannel newFileChannel} method on the
 208      * provider that created the {@code Path}.
 209      *
 210      * @param   file
 211      *          The path of the file to open or create
 212      * @param   options
 213      *          Options specifying how the file is opened
 214      * @param   executor
 215      *          The thread pool or {@code null} to associate the channel with
 216      *          the default thread pool
 217      * @param   attrs
 218      *          An optional list of file attributes to set atomically when
 219      *          creating the file
 220      *
 221      * @return  A new asynchronous file channel
 222      *
 223      * @throws  IllegalArgumentException
 224      *          If the set contains an invalid combination of options
 225      * @throws  UnsupportedOperationException
 226      *          If the {@code file} is associated with a provider that does not
 227      *          support creating asynchronous file channels, or an unsupported
 228      *          open option is specified, or the array contains an attribute that
 229      *          cannot be set atomically when creating the file
 230      * @throws  IOException
 231      *          If an I/O error occurs
 232      * @throws  SecurityException
 233      *          If a security manager is installed and it denies an
 234      *          unspecified permission required by the implementation.
 235      *          In the case of the default provider, the {@link
 236      *          SecurityManager#checkRead(String)} method is invoked to check
 237      *          read access if the file is opened for reading. The {@link
 238      *          SecurityManager#checkWrite(String)} method is invoked to check
 239      *          write access if the file is opened for writing
 240      */
 241     public static AsynchronousFileChannel open(Path file,
 242                                                Set<? extends OpenOption> options,
 243                                                ExecutorService executor,
 244                                                FileAttribute<?>... attrs)
 245         throws IOException
 246     {
 247         FileSystemProvider provider = file.getFileSystem().provider();
 248         return provider.newAsynchronousFileChannel(file, options, executor, attrs);
 249     }
 250 
 251     private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
 252 
 253     /**
 254      * Opens or creates a file for reading and/or writing, returning an
 255      * asynchronous file channel to access the file.
 256      *
 257      * <p> An invocation of this method behaves in exactly the same way as the
 258      * invocation
 259      * <pre>
 260      *     ch.{@link #open(Path,Set,ExecutorService,FileAttribute[])
 261      *       open}(file, opts, null, new FileAttribute&lt;?&gt;[0]);
 262      * </pre>
 263      * where {@code opts} is a {@code Set} containing the options specified to
 264      * this method.
 265      *
 266      * <p> The resulting channel is associated with default thread pool to which
 267      * tasks are submitted to handle I/O events and dispatch to completion
 268      * handlers that consume the result of asynchronous operations performed on
 269      * the resulting channel.
 270      *
 271      * @param   file
 272      *          The path of the file to open or create
 273      * @param   options
 274      *          Options specifying how the file is opened
 275      *
 276      * @return  A new asynchronous file channel
 277      *
 278      * @throws  IllegalArgumentException
 279      *          If the set contains an invalid combination of options
 280      * @throws  UnsupportedOperationException
 281      *          If the {@code file} is associated with a provider that does not
 282      *          support creating file channels, or an unsupported open option is
 283      *          specified
 284      * @throws  IOException
 285      *          If an I/O error occurs
 286      * @throws  SecurityException
 287      *          If a security manager is installed and it denies an
 288      *          unspecified permission required by the implementation.
 289      *          In the case of the default provider, the {@link
 290      *          SecurityManager#checkRead(String)} method is invoked to check
 291      *          read access if the file is opened for reading. The {@link
 292      *          SecurityManager#checkWrite(String)} method is invoked to check
 293      *          write access if the file is opened for writing
 294      */
 295     public static AsynchronousFileChannel open(Path file, OpenOption... options)
 296         throws IOException
 297     {
 298         Set<OpenOption> set = new HashSet<OpenOption>(options.length);
 299         Collections.addAll(set, options);
 300         return open(file, set, null, NO_ATTRIBUTES);
 301     }
 302 
 303     /**
 304      * Returns the current size of this channel's file.
 305      *
 306      * @return  The current size of this channel's file, measured in bytes
 307      *
 308      * @throws  ClosedChannelException
 309      *          If this channel is closed
 310      * @throws  IOException
 311      *          If some other I/O error occurs
 312      */
 313     public abstract long size() throws IOException;
 314 
 315     /**
 316      * Truncates this channel's file to the given size.
 317      *
 318      * <p> If the given size is less than the file's current size then the file
 319      * is truncated, discarding any bytes beyond the new end of the file.  If
 320      * the given size is greater than or equal to the file's current size then
 321      * the file is not modified. </p>
 322      *
 323      * @param  size
 324      *         The new size, a non-negative byte count
 325      *
 326      * @return  This file channel
 327      *
 328      * @throws  NonWritableChannelException
 329      *          If this channel was not opened for writing
 330      *
 331      * @throws  ClosedChannelException
 332      *          If this channel is closed
 333      *
 334      * @throws  IllegalArgumentException
 335      *          If the new size is negative
 336      *
 337      * @throws  IOException
 338      *          If some other I/O error occurs
 339      */
 340     public abstract AsynchronousFileChannel truncate(long size) throws IOException;
 341 
 342     /**
 343      * Forces any updates to this channel's file to be written to the storage
 344      * device that contains it.
 345      *
 346      * <p> If this channel's file resides on a local storage device then when
 347      * this method returns it is guaranteed that all changes made to the file
 348      * since this channel was created, or since this method was last invoked,
 349      * will have been written to that device.  This is useful for ensuring that
 350      * critical information is not lost in the event of a system crash.
 351      *
 352      * <p> If the file does not reside on a local device then no such guarantee
 353      * is made.
 354      *
 355      * <p> The {@code metaData} parameter can be used to limit the number of
 356      * I/O operations that this method is required to perform.  Passing
 357      * {@code false} for this parameter indicates that only updates to the
 358      * file's content need be written to storage; passing {@code true}
 359      * indicates that updates to both the file's content and metadata must be
 360      * written, which generally requires at least one more I/O operation.
 361      * Whether this parameter actually has any effect is dependent upon the
 362      * underlying operating system and is therefore unspecified.
 363      *
 364      * <p> Invoking this method may cause an I/O operation to occur even if the
 365      * channel was only opened for reading.  Some operating systems, for
 366      * example, maintain a last-access time as part of a file's metadata, and
 367      * this time is updated whenever the file is read.  Whether or not this is
 368      * actually done is system-dependent and is therefore unspecified.
 369      *
 370      * <p> This method is only guaranteed to force changes that were made to
 371      * this channel's file via the methods defined in this class.
 372      *
 373      * @param   metaData
 374      *          If {@code true} then this method is required to force changes
 375      *          to both the file's content and metadata to be written to
 376      *          storage; otherwise, it need only force content changes to be
 377      *          written
 378      *
 379      * @throws  ClosedChannelException
 380      *          If this channel is closed
 381      *
 382      * @throws  IOException
 383      *          If some other I/O error occurs
 384      */
 385     public abstract void force(boolean metaData) throws IOException;
 386 
 387     /**
 388      * Acquires a lock on the given region of this channel's file.
 389      *
 390      * <p> This method initiates an operation to acquire a lock on the given
 391      * region of this channel's file. The {@code handler} parameter is a
 392      * completion handler that is invoked when the lock is acquired (or the
 393      * operation fails). The result passed to the completion handler is the
 394      * resulting {@code FileLock}.
 395      *
 396      * <p> The region specified by the {@code position} and {@code size}
 397      * parameters need not be contained within, or even overlap, the actual
 398      * underlying file.  Lock regions are fixed in size; if a locked region
 399      * initially contains the end of the file and the file grows beyond the
 400      * region then the new portion of the file will not be covered by the lock.
 401      * If a file is expected to grow in size and a lock on the entire file is
 402      * required then a region starting at zero, and no smaller than the
 403      * expected maximum size of the file, should be locked.  The two-argument
 404      * {@link #lock(Object,CompletionHandler)} method simply locks a region
 405      * of size {@link Long#MAX_VALUE}. If a lock that overlaps the requested
 406      * region is already held by this Java virtual machine, or this method has
 407      * been invoked to lock an overlapping region and that operation has not
 408      * completed, then this method throws {@link OverlappingFileLockException}.
 409      *
 410      * <p> Some operating systems do not support a mechanism to acquire a file
 411      * lock in an asynchronous manner. Consequently an implementation may
 412      * acquire the file lock in a background thread or from a task executed by
 413      * a thread in the associated thread pool. If there are many lock operations
 414      * outstanding then it may consume threads in the Java virtual machine for
 415      * indefinite periods.
 416      *
 417      * <p> Some operating systems do not support shared locks, in which case a
 418      * request for a shared lock is automatically converted into a request for
 419      * an exclusive lock.  Whether the newly-acquired lock is shared or
 420      * exclusive may be tested by invoking the resulting lock object's {@link
 421      * FileLock#isShared() isShared} method.
 422      *
 423      * <p> File locks are held on behalf of the entire Java virtual machine.
 424      * They are not suitable for controlling access to a file by multiple
 425      * threads within the same virtual machine.
 426      *
 427      * @param   position
 428      *          The position at which the locked region is to start; must be
 429      *          non-negative
 430      * @param   size
 431      *          The size of the locked region; must be non-negative, and the sum
 432      *          {@code position}&nbsp;+&nbsp;{@code size} must be non-negative
 433      * @param   shared
 434      *          {@code true} to request a shared lock, in which case this
 435      *          channel must be open for reading (and possibly writing);
 436      *          {@code false} to request an exclusive lock, in which case this
 437      *          channel must be open for writing (and possibly reading)
 438      * @param   attachment
 439      *          The object to attach to the I/O operation; can be {@code null}
 440      * @param   handler
 441      *          The handler for consuming the result
 442      *
 443      * @throws  OverlappingFileLockException
 444      *          If a lock that overlaps the requested region is already held by
 445      *          this Java virtual machine, or there is already a pending attempt
 446      *          to lock an overlapping region
 447      * @throws  IllegalArgumentException
 448      *          If the preconditions on the parameters do not hold
 449      * @throws  NonReadableChannelException
 450      *          If {@code shared} is true but this channel was not opened for reading
 451      * @throws  NonWritableChannelException
 452      *          If {@code shared} is false but this channel was not opened for writing
 453      */
 454     public abstract <A> void lock(long position,
 455                                   long size,
 456                                   boolean shared,
 457                                   A attachment,
 458                                   CompletionHandler<FileLock,? super A> handler);
 459 
 460     /**
 461      * Acquires an exclusive lock on this channel's file.
 462      *
 463      * <p> This method initiates an operation to acquire a lock on the given
 464      * region of this channel's file. The {@code handler} parameter is a
 465      * completion handler that is invoked when the lock is acquired (or the
 466      * operation fails). The result passed to the completion handler is the
 467      * resulting {@code FileLock}.
 468      *
 469      * <p> An invocation of this method of the form {@code ch.lock(att,handler)}
 470      * behaves in exactly the same way as the invocation
 471      * <pre>
 472      *     ch.{@link #lock(long,long,boolean,Object,CompletionHandler) lock}(0L, Long.MAX_VALUE, false, att, handler)
 473      * </pre>
 474      *
 475      * @param   attachment
 476      *          The object to attach to the I/O operation; can be {@code null}
 477      * @param   handler
 478      *          The handler for consuming the result
 479      *
 480      * @throws  OverlappingFileLockException
 481      *          If a lock is already held by this Java virtual machine, or there
 482      *          is already a pending attempt to lock a region
 483      * @throws  NonWritableChannelException
 484      *          If this channel was not opened for writing
 485      */
 486     public final <A> void lock(A attachment,
 487                                CompletionHandler<FileLock,? super A> handler)
 488     {
 489         lock(0L, Long.MAX_VALUE, false, attachment, handler);
 490     }
 491 
 492     /**
 493      * Acquires a lock on the given region of this channel's file.
 494      *
 495      * <p> This method initiates an operation to acquire a lock on the given
 496      * region of this channel's file.  The method behaves in exactly the same
 497      * manner as the {@link #lock(long, long, boolean, Object, CompletionHandler)}
 498      * method except that instead of specifying a completion handler, this
 499      * method returns a {@code Future} representing the pending result. The
 500      * {@code Future}'s {@link Future#get() get} method returns the {@link
 501      * FileLock} on successful completion.
 502      *
 503      * @param   position
 504      *          The position at which the locked region is to start; must be
 505      *          non-negative
 506      * @param   size
 507      *          The size of the locked region; must be non-negative, and the sum
 508      *          {@code position}&nbsp;+&nbsp;{@code size} must be non-negative
 509      * @param   shared
 510      *          {@code true} to request a shared lock, in which case this
 511      *          channel must be open for reading (and possibly writing);
 512      *          {@code false} to request an exclusive lock, in which case this
 513      *          channel must be open for writing (and possibly reading)
 514      *
 515      * @return  a {@code Future} object representing the pending result
 516      *
 517      * @throws  OverlappingFileLockException
 518      *          If a lock is already held by this Java virtual machine, or there
 519      *          is already a pending attempt to lock a region
 520      * @throws  IllegalArgumentException
 521      *          If the preconditions on the parameters do not hold
 522      * @throws  NonReadableChannelException
 523      *          If {@code shared} is true but this channel was not opened for reading
 524      * @throws  NonWritableChannelException
 525      *          If {@code shared} is false but this channel was not opened for writing
 526      */
 527     public abstract Future<FileLock> lock(long position, long size, boolean shared);
 528 
 529     /**
 530      * Acquires an exclusive lock on this channel's file.
 531      *
 532      * <p> This method initiates an operation to acquire an exclusive lock on this
 533      * channel's file. The method returns a {@code Future} representing the
 534      * pending result of the operation. The {@code Future}'s {@link Future#get()
 535      * get} method returns the {@link FileLock} on successful completion.
 536      *
 537      * <p> An invocation of this method behaves in exactly the same way as the
 538      * invocation
 539      * <pre>
 540      *     ch.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false)
 541      * </pre>
 542      *
 543      * @return  a {@code Future} object representing the pending result
 544      *
 545      * @throws  OverlappingFileLockException
 546      *          If a lock is already held by this Java virtual machine, or there
 547      *          is already a pending attempt to lock a region
 548      * @throws  NonWritableChannelException
 549      *          If this channel was not opened for writing
 550      */
 551     public final Future<FileLock> lock() {
 552         return lock(0L, Long.MAX_VALUE, false);
 553     }
 554 
 555     /**
 556      * Attempts to acquire a lock on the given region of this channel's file.
 557      *
 558      * <p> This method does not block. An invocation always returns immediately,
 559      * either having acquired a lock on the requested region or having failed to
 560      * do so.  If it fails to acquire a lock because an overlapping lock is held
 561      * by another program then it returns {@code null}.  If it fails to acquire
 562      * a lock for any other reason then an appropriate exception is thrown.
 563      *
 564      * @param  position
 565      *         The position at which the locked region is to start; must be
 566      *         non-negative
 567      *
 568      * @param  size
 569      *         The size of the locked region; must be non-negative, and the sum
 570      *         {@code position}&nbsp;+&nbsp;{@code size} must be non-negative
 571      *
 572      * @param  shared
 573      *         {@code true} to request a shared lock,
 574      *         {@code false} to request an exclusive lock
 575      *
 576      * @return  A lock object representing the newly-acquired lock,
 577      *          or {@code null} if the lock could not be acquired
 578      *          because another program holds an overlapping lock
 579      *
 580      * @throws  IllegalArgumentException
 581      *          If the preconditions on the parameters do not hold
 582      * @throws  ClosedChannelException
 583      *          If this channel is closed
 584      * @throws  OverlappingFileLockException
 585      *          If a lock that overlaps the requested region is already held by
 586      *          this Java virtual machine, or if another thread is already
 587      *          blocked in this method and is attempting to lock an overlapping
 588      *          region of the same file
 589      * @throws  NonReadableChannelException
 590      *          If {@code shared} is true but this channel was not opened for reading
 591      * @throws  NonWritableChannelException
 592      *          If {@code shared} is false but this channel was not opened for writing
 593      *
 594      * @throws  IOException
 595      *          If some other I/O error occurs
 596      *
 597      * @see     #lock(Object,CompletionHandler)
 598      * @see     #lock(long,long,boolean,Object,CompletionHandler)
 599      * @see     #tryLock()
 600      */
 601     public abstract FileLock tryLock(long position, long size, boolean shared)
 602         throws IOException;
 603 
 604     /**
 605      * Attempts to acquire an exclusive lock on this channel's file.
 606      *
 607      * <p> An invocation of this method of the form {@code ch.tryLock()}
 608      * behaves in exactly the same way as the invocation
 609      *
 610      * <pre>
 611      *     ch.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre>
 612      *
 613      * @return  A lock object representing the newly-acquired lock,
 614      *          or {@code null} if the lock could not be acquired
 615      *          because another program holds an overlapping lock
 616      *
 617      * @throws  ClosedChannelException
 618      *          If this channel is closed
 619      * @throws  OverlappingFileLockException
 620      *          If a lock that overlaps the requested region is already held by
 621      *          this Java virtual machine, or if another thread is already
 622      *          blocked in this method and is attempting to lock an overlapping
 623      *          region
 624      * @throws  NonWritableChannelException
 625      *          If {@code shared} is false but this channel was not opened for writing
 626      *
 627      * @throws  IOException
 628      *          If some other I/O error occurs
 629      *
 630      * @see     #lock(Object,CompletionHandler)
 631      * @see     #lock(long,long,boolean,Object,CompletionHandler)
 632      * @see     #tryLock(long,long,boolean)
 633      */
 634     public final FileLock tryLock() throws IOException {
 635         return tryLock(0L, Long.MAX_VALUE, false);
 636     }
 637 
 638     /**
 639      * Reads a sequence of bytes from this channel into the given buffer,
 640      * starting at the given file position.
 641      *
 642      * <p> This method initiates the reading of a sequence of bytes from this
 643      * channel into the given buffer, starting at the given file position. The
 644      * result of the read is the number of bytes read or {@code -1} if the given
 645      * position is greater than or equal to the file's size at the time that the
 646      * read is attempted.
 647      *
 648      * <p> This method works in the same manner as the {@link
 649      * AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)}
 650      * method, except that bytes are read starting at the given file position.
 651      * If the given file position is greater than the file's size at the time
 652      * that the read is attempted then no bytes are read.
 653      *
 654      * @param   dst
 655      *          The buffer into which bytes are to be transferred
 656      * @param   position
 657      *          The file position at which the transfer is to begin;
 658      *          must be non-negative
 659      * @param   attachment
 660      *          The object to attach to the I/O operation; can be {@code null}
 661      * @param   handler
 662      *          The handler for consuming the result
 663      *
 664      * @throws  IllegalArgumentException
 665      *          If the position is negative or the buffer is read-only
 666      * @throws  NonReadableChannelException
 667      *          If this channel was not opened for reading
 668      */
 669     public abstract <A> void read(ByteBuffer dst,
 670                                   long position,
 671                                   A attachment,
 672                                   CompletionHandler<Integer,? super A> handler);
 673 
 674     /**
 675      * Reads a sequence of bytes from this channel into the given buffer,
 676      * starting at the given file position.
 677      *
 678      * <p> This method initiates the reading of a sequence of bytes from this
 679      * channel into the given buffer, starting at the given file position. This
 680      * method returns a {@code Future} representing the pending result of the
 681      * operation. The {@code Future}'s {@link Future#get() get} method returns
 682      * the number of bytes read or {@code -1} if the given position is greater
 683      * than or equal to the file's size at the time that the read is attempted.
 684      *
 685      * <p> This method works in the same manner as the {@link
 686      * AsynchronousByteChannel#read(ByteBuffer)} method, except that bytes are
 687      * read starting at the given file position. If the given file position is
 688      * greater than the file's size at the time that the read is attempted then
 689      * no bytes are read.
 690      *
 691      * @param   dst
 692      *          The buffer into which bytes are to be transferred
 693      * @param   position
 694      *          The file position at which the transfer is to begin;
 695      *          must be non-negative
 696      *
 697      * @return  A {@code Future} object representing the pending result
 698      *
 699      * @throws  IllegalArgumentException
 700      *          If the position is negative or the buffer is read-only
 701      * @throws  NonReadableChannelException
 702      *          If this channel was not opened for reading
 703      */
 704     public abstract Future<Integer> read(ByteBuffer dst, long position);
 705 
 706     /**
 707      * Writes a sequence of bytes to this channel from the given buffer, starting
 708      * at the given file position.
 709      *
 710      * <p> This method works in the same manner as the {@link
 711      * AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)}
 712      * method, except that bytes are written starting at the given file position.
 713      * If the given position is greater than the file's size, at the time that
 714      * the write is attempted, then the file will be grown to accommodate the new
 715      * bytes; the values of any bytes between the previous end-of-file and the
 716      * newly-written bytes are unspecified.
 717      *
 718      * @param   src
 719      *          The buffer from which bytes are to be transferred
 720      * @param   position
 721      *          The file position at which the transfer is to begin;
 722      *          must be non-negative
 723      * @param   attachment
 724      *          The object to attach to the I/O operation; can be {@code null}
 725      * @param   handler
 726      *          The handler for consuming the result
 727      *
 728      * @throws  IllegalArgumentException
 729      *          If the position is negative
 730      * @throws  NonWritableChannelException
 731      *          If this channel was not opened for writing
 732      */
 733     public abstract <A> void write(ByteBuffer src,
 734                                    long position,
 735                                    A attachment,
 736                                    CompletionHandler<Integer,? super A> handler);
 737 
 738     /**
 739      * Writes a sequence of bytes to this channel from the given buffer, starting
 740      * at the given file position.
 741      *
 742      * <p> This method initiates the writing of a sequence of bytes to this
 743      * channel from the given buffer, starting at the given file position. The
 744      * method returns a {@code Future} representing the pending result of the
 745      * write operation. The {@code Future}'s {@link Future#get() get} method
 746      * returns the number of bytes written.
 747      *
 748      * <p> This method works in the same manner as the {@link
 749      * AsynchronousByteChannel#write(ByteBuffer)} method, except that bytes are
 750      * written starting at the given file position. If the given position is
 751      * greater than the file's size, at the time that the write is attempted,
 752      * then the file will be grown to accommodate the new bytes; the values of
 753      * any bytes between the previous end-of-file and the newly-written bytes
 754      * are unspecified.
 755      *
 756      * @param   src
 757      *          The buffer from which bytes are to be transferred
 758      * @param   position
 759      *          The file position at which the transfer is to begin;
 760      *          must be non-negative
 761      *
 762      * @return  A {@code Future} object representing the pending result
 763      *
 764      * @throws  IllegalArgumentException
 765      *          If the position is negative
 766      * @throws  NonWritableChannelException
 767      *          If this channel was not opened for writing
 768      */
 769     public abstract Future<Integer> write(ByteBuffer src, long position);
 770 }