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