A channel for reading, writing, mapping, and manipulating a file.

A file channel has a current position within its file which can be both queried and modified . The file itself contains a variable-length sequence of bytes that can be read and written and whose current size can be queried. The size of the file increases when bytes are written beyond its current size; the size of the file decreases when it is truncated . The file may also have some associated metadata such as access permissions, content type, and last-modification time; this class does not define methods for metadata access.

In addition to the familiar read, write, and close operations of byte channels, this class defines the following file-specific operations:

File channels are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. Only one operation that involves the channel's position or can change its file's size may be in progress at any given time; attempts to initiate a second such operation while the first is still in progress will block until the first operation completes. Other operations, in particular those that take an explicit position, may proceed concurrently; whether they in fact do so is dependent upon the underlying implementation and is therefore unspecified.

The view of a file provided by an instance of this class is guaranteed to be consistent with other views of the same file provided by other instances in the same program. The view provided by an instance of this class may or may not, however, be consistent with the views seen by other concurrently-running programs due to caching performed by the underlying operating system and delays induced by network-filesystem protocols. This is true regardless of the language in which these other programs are written, and whether they are running on the same machine or on some other machine. The exact nature of any such inconsistencies are system-dependent and are therefore unspecified.

This class does not define methods for opening existing files or for creating new ones; such methods may be added in a future release. In this release a file channel can be obtained from an existing FileInputStream , FileOutputStream , or RandomAccessFile object by invoking that object's getChannel method, which returns a file channel that is connected to the same underlying file.

The state of a file channel is intimately connected to that of the object whose getChannel method returned the channel. Changing the channel's position, whether explicitly or by reading or writing bytes, will change the file position of the originating object, and vice versa. Changing the file's length via the file channel will change the length seen via the originating object, and vice versa. Changing the file's content by writing bytes will change the content seen by the originating object, and vice versa.

At various points this class specifies that an instance that is "open for reading," "open for writing," or "open for reading and writing" is required. A channel obtained via the getChannel method of a java.io.FileInputStream instance will be open for reading. A channel obtained via the getChannel method of a java.io.FileOutputStream instance will be open for writing. Finally, a channel obtained via the getChannel method of a java.io.RandomAccessFile instance will be open for reading if the instance was created with mode "r" and will be open for reading and writing if the instance was created with mode "rw".

A file channel that is open for writing may be in append mode, for example if it was obtained from a file-output stream that was created by invoking the FileOutputStream(File,boolean) constructor and passing true for the second parameter. In this mode each invocation of a relative write operation first advances the position to the end of the file and then writes the requested data. Whether the advancement of the position and the writing of the data are done in a single atomic operation is system-dependent and therefore unspecified.

@author
Mark Reinhold
@author
Mike McCloskey
@author
JSR-51 Expert Group
@version
1.40, 04/01/12
@since
1.4
Closes this channel.

If the channel has already been closed then this method returns immediately. Otherwise it marks the channel as closed and then invokes the implCloseChannel method in order to complete the close operation.

Throws
IOException If an I/O error occurs
Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Parameters
objthe reference object with which to compare.
Return
true if this object is the same as the obj argument; false otherwise.
Forces any updates to this channel's file to be written to the storage device that contains it.

If this channel's file resides on a local storage device then when this method returns it is guaranteed that all changes made to the file since this channel was created, or since this method was last invoked, will have been written to that device. This is useful for ensuring that critical information is not lost in the event of a system crash.

If the file does not reside on a local device then no such guarantee is made.

The metaData parameter can be used to limit the number of I/O operations that this method is required to perform. Passing false for this parameter indicates that only updates to the file's content need be written to storage; passing true indicates that updates to both the file's content and metadata must be written, which generally requires at least one more I/O operation. Whether this parameter actually has any effect is dependent upon the underlying operating system and is therefore unspecified.

Invoking this method may cause an I/O operation to occur even if the channel was only opened for reading. Some operating systems, for example, maintain a last-access time as part of a file's metadata, and this time is updated whenever the file is read. Whether or not this is actually done is system-dependent and is therefore unspecified.

This method is only guaranteed to force changes that were made to this channel's file via the methods defined in this class. It may or may not force changes that were made by modifying the content of a mapped byte buffer obtained by invoking the map method. Invoking the force method of the mapped byte buffer will force changes made to the buffer's content to be written.

Parameters
metaData If true then this method is required to force changes to both the file's content and metadata to be written to storage; otherwise, it need only force content changes to be written
Throws
ClosedChannelException If this channel is closed
IOException If some other I/O error occurs
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Return
a hash code value for this object.
Acquires an exclusive lock on this channel's file.

An invocation of this method of the form fc.lock() behaves in exactly the same way as the invocation

     fc.lock
(0L, Long.MAX_VALUE, false) 
Return
A lock object representing the newly-acquired lock
Throws
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the invoking thread is blocked in this method
FileLockInterruptionException If the invoking thread is interrupted while blocked in this method
OverlappingFileLockException If a lock that overlaps the requested region is already held by this Java virtual machine, or if another thread is already blocked in this method and is attempting to lock an overlapping region of the same file
NonReadableChannelException If shared is true this channel was not opened for reading
NonWritableChannelException If shared is false but this channel was not opened for writing
IOException If some other I/O error occurs
Acquires a lock on the given region of this channel's file.

An invocation of this method will block until the region can be locked, this channel is closed, or the invoking thread is interrupted, whichever comes first.

If this channel is closed by another thread during an invocation of this method then an AsynchronousCloseException will be thrown.

If the invoking thread is interrupted while waiting to acquire the lock then its interrupt status will be set and a FileLockInterruptionException will be thrown. If the invoker's interrupt status is set when this method is invoked then that exception will be thrown immediately; the thread's interrupt status will not be changed.

The region specified by the position and size parameters need not be contained within, or even overlap, the actual underlying file. Lock regions are fixed in size; if a locked region initially contains the end of the file and the file grows beyond the region then the new portion of the file will not be covered by the lock. If a file is expected to grow in size and a lock on the entire file is required then a region starting at zero, and no smaller than the expected maximum size of the file, should be locked. The zero-argument method simply locks a region of size Long#MAX_VALUE .

Some operating systems do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock. Whether the newly-acquired lock is shared or exclusive may be tested by invoking the resulting lock object's isShared method.

File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.

Parameters
position The position at which the locked region is to start; must be non-negative
size The size of the locked region; must be non-negative, and the sum position + size must be non-negative
shared true to request a shared lock, in which case this channel must be open for reading (and possibly writing); false to request an exclusive lock, in which case this channel must be open for writing (and possibly reading)
Return
A lock object representing the newly-acquired lock
Throws
IllegalArgumentException If the preconditions on the parameters do not hold
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the invoking thread is blocked in this method
FileLockInterruptionException If the invoking thread is interrupted while blocked in this method
OverlappingFileLockException If a lock that overlaps the requested region is already held by this Java virtual machine, or if another thread is already blocked in this method and is attempting to lock an overlapping region
NonReadableChannelException If shared is true this channel was not opened for reading
NonWritableChannelException If shared is false but this channel was not opened for writing
IOException If some other I/O error occurs
Maps a region of this channel's file directly into memory.

A region of a file may be mapped into memory in one of three modes:

  • Read-only: Any attempt to modify the resulting buffer will cause a java.nio.ReadOnlyBufferException to be thrown. (MapMode.READ_ONLY )

  • Read/write: Changes made to the resulting buffer will eventually be propagated to the file; they may or may not be made visible to other programs that have mapped the same file. (MapMode.READ_WRITE )

  • Private: Changes made to the resulting buffer will not be propagated to the file and will not be visible to other programs that have mapped the same file; instead, they will cause private copies of the modified portions of the buffer to be created. (MapMode.PRIVATE )

For a read-only mapping, this channel must have been opened for reading; for a read/write or private mapping, this channel must have been opened for both reading and writing.

The mapped byte buffer returned by this method will have a position of zero and a limit and capacity of size; its mark will be undefined. The buffer and the mapping that it represents will remain valid until the buffer itself is garbage-collected.

A mapping, once established, is not dependent upon the file channel that was used to create it. Closing the channel, in particular, has no effect upon the validity of the mapping.

Many of the details of memory-mapped files are inherently dependent upon the underlying operating system and are therefore unspecified. The behavior of this method when the requested region is not completely contained within this channel's file is unspecified. Whether changes made to the content or size of the underlying file, by this program or another, are propagated to the buffer is unspecified. The rate at which changes to the buffer are propagated to the file is unspecified.

For most operating systems, mapping a file into memory is more expensive than reading or writing a few tens of kilobytes of data via the usual read and write methods. From the standpoint of performance it is generally only worth mapping relatively large files into memory.

Parameters
mode One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE PRIVATE} defined in the {@link MapMode} class, according to whether the file is to be mapped read-only, read/write, or privately (copy-on-write), respectively
position The position within the file at which the mapped region is to start; must be non-negative
size The size of the region to be mapped; must be non-negative and no greater than {@link java.lang.Integer#MAX_VALUE}
Throws
NonReadableChannelException If the mode is {@link MapMode#READ_ONLY READ_ONLY} but this channel was not opened for reading
NonWritableChannelException If the mode is {@link MapMode#READ_WRITE READ_WRITE} or {@link MapMode#PRIVATE PRIVATE} but this channel was not opened for both reading and writing
IllegalArgumentException If the preconditions on the parameters do not hold
IOException If some other I/O error occurs
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Returns this channel's file position.

Return
This channel's file position, a non-negative integer counting the number of bytes from the beginning of the file to the current position
Throws
ClosedChannelException If this channel is closed
IOException If some other I/O error occurs
Sets this channel's file position.

Setting the position to a value that is greater than the file's current size is legal but does not change the size of the file. A later attempt to read bytes at such a position will immediately return an end-of-file indication. A later attempt to write bytes at such a position will cause the file to be grown to accommodate the new bytes; the values of any bytes between the previous end-of-file and the newly-written bytes are unspecified.

Parameters
newPosition The new position, a non-negative integer counting the number of bytes from the beginning of the file
Return
This file channel
Throws
ClosedChannelException If this channel is closed
IllegalArgumentException If the new position is negative
IOException If some other I/O error occurs
Reads a sequence of bytes from this channel into the given buffer.

Bytes are read starting at this channel's current file position, and then the file position is updated with the number of bytes actually read. Otherwise this method behaves exactly as specified in the ReadableByteChannel interface.

Reads a sequence of bytes from this channel into the given buffers.

An invocation of this method of the form c.read(dsts) behaves in exactly the same manner as the invocation

 c.read(dsts, 0, srcs.length);
Parameters
dsts The buffers into which bytes are to be transferred
Return
The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream
Throws
NonReadableChannelException If this channel was not opened for reading
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the read operation is in progress
ClosedByInterruptException If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt status
IOException If some other I/O error occurs
Reads a sequence of bytes from this channel into a subsequence of the given buffers.

An invocation of this method attempts to read up to r bytes from this channel, where r is the total number of bytes remaining the specified subsequence of the given buffer array, that is,

 dsts[offset].remaining()
     + dsts[offset+1].remaining()
     + ... + dsts[offset+length-1].remaining()
at the moment that this method is invoked.

Suppose that a byte sequence of length n is read, where 0 <= n <= r. Up to the first dsts[offset].remaining() bytes of this sequence are transferred into buffer dsts[offset], up to the next dsts[offset+1].remaining() bytes are transferred into buffer dsts[offset+1], and so forth, until the entire byte sequence is transferred into the given buffers. As many bytes as possible are transferred into each buffer, hence the final position of each updated buffer, except the last updated buffer, is guaranteed to be equal to that buffer's limit.

This method may be invoked at any time. If another thread has already initiated a read operation upon this channel, however, then an invocation of this method will block until the first operation is complete.

Parameters
dsts The buffers into which bytes are to be transferred
offset The offset within the buffer array of the first buffer into which bytes are to be transferred; must be non-negative and no larger than dsts.length
length The maximum number of buffers to be accessed; must be non-negative and no larger than dsts.length - offset
Return
The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream
Throws
IndexOutOfBoundsException If the preconditions on the offset and length parameters do not hold
NonReadableChannelException If this channel was not opened for reading
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the read operation is in progress
ClosedByInterruptException If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt status
IOException If some other I/O error occurs
Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.

This method works in the same manner as the method, except that bytes are read starting at the given file position rather than at the channel's current position. This method does not modify this channel's position. If the given position is greater than the file's current size then no bytes are read.

Parameters
dst The buffer into which bytes are to be transferred
position The file position at which the transfer is to begin; must be non-negative
Return
The number of bytes read, possibly zero, or -1 if the given position is greater than or equal to the file's current size
Throws
IllegalArgumentException If the position is negative
NonReadableChannelException If this channel was not opened for reading
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the read operation is in progress
ClosedByInterruptException If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt status
IOException If some other I/O error occurs
Returns the current size of this channel's file.

Return
The current size of this channel's file, measured in bytes
Throws
ClosedChannelException If this channel is closed
IOException If some other I/O error occurs
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 
Return
a string representation of the object.
Transfers bytes into this channel's file from the given readable byte channel.

An attempt is made to read up to count bytes from the source channel and write them to this channel's file starting at the given position. An invocation of this method may or may not transfer all of the requested bytes; whether or not it does so depends upon the natures and states of the channels. Fewer than the requested number of bytes will be transferred if the source channel has fewer than count bytes remaining, or if the source channel is non-blocking and has fewer than count bytes immediately available in its input buffer.

This method does not modify this channel's position. If the given position is greater than the file's current size then no bytes are transferred. If the source channel has a position then bytes are read starting at that position and then the position is incremented by the number of bytes read.

This method is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.

Parameters
src The source channel
position The position within the file at which the transfer is to begin; must be non-negative
count The maximum number of bytes to be transferred; must be non-negative
Return
The number of bytes, possibly zero, that were actually transferred
Throws
IllegalArgumentException If the preconditions on the parameters do not hold
NonReadableChannelException If the source channel was not opened for reading
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If either this channel or the source channel is closed
AsynchronousCloseException If another thread closes either channel while the transfer is in progress
ClosedByInterruptException If another thread interrupts the current thread while the transfer is in progress, thereby closing both channels and setting the current thread's interrupt status
IOException If some other I/O error occurs
Transfers bytes from this channel's file to the given writable byte channel.

An attempt is made to read up to count bytes starting at the given position in this channel's file and write them to the target channel. An invocation of this method may or may not transfer all of the requested bytes; whether or not it does so depends upon the natures and states of the channels. Fewer than the requested number of bytes are transferred if this channel's file contains fewer than count bytes starting at the given position, or if the target channel is non-blocking and it has fewer than count bytes free in its output buffer.

This method does not modify this channel's position. If the given position is greater than the file's current size then no bytes are transferred. If the target channel has a position then bytes are written starting at that position and then the position is incremented by the number of bytes written.

This method is potentially much more efficient than a simple loop that reads from this channel and writes to the target channel. Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.

Parameters
position The position within the file at which the transfer is to begin; must be non-negative
count The maximum number of bytes to be transferred; must be non-negative
target The target channel
Return
The number of bytes, possibly zero, that were actually transferred
Throws
IllegalArgumentException If the preconditions on the parameters do not hold
NonReadableChannelException If this channel was not opened for reading
NonWritableChannelException If the target channel was not opened for writing
ClosedChannelException If either this channel or the target channel is closed
AsynchronousCloseException If another thread closes either channel while the transfer is in progress
ClosedByInterruptException If another thread interrupts the current thread while the transfer is in progress, thereby closing both channels and setting the current thread's interrupt status
IOException If some other I/O error occurs
Truncates this channel's file to the given size.

If the given size is less than the file's current size then the file is truncated, discarding any bytes beyond the new end of the file. If the given size is greater than or equal to the file's current size then the file is not modified. In either case, if this channel's file position is greater than the given size then it is set to that size.

Parameters
size The new size, a non-negative byte count
Return
This file channel
Throws
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If this channel is closed
IllegalArgumentException If the new size is negative
IOException If some other I/O error occurs
Attempts to acquire an exclusive lock on this channel's file.

An invocation of this method of the form fc.tryLock() behaves in exactly the same way as the invocation

     fc.tryLock
(0L, Long.MAX_VALUE, false) 
Return
A lock object representing the newly-acquired lock, or null if the lock could not be acquired because another program holds an overlapping lock
Throws
ClosedChannelException If this channel is closed
OverlappingFileLockException If a lock that overlaps the requested region is already held by this Java virtual machine, or if another thread is already blocked in this method and is attempting to lock an overlapping region
IOException If some other I/O error occurs
Attempts to acquire a lock on the given region of this channel's file.

This method does not block. An invocation of this always returns immediately, either having acquired a lock on the requested region or having failed to do so. If it fails to acquire a lock because an overlapping lock is held by another program then it returns null. If it fails to acquire a lock for any other reason then an appropriate exception is thrown.

The region specified by the position and size parameters need not be contained within, or even overlap, the actual underlying file. Lock regions are fixed in size; if a locked region initially contains the end of the file and the file grows beyond the region then the new portion of the file will not be covered by the lock. If a file is expected to grow in size and a lock on the entire file is required then a region starting at zero, and no smaller than the expected maximum size of the file, should be locked. The zero-argument method simply locks a region of size Long#MAX_VALUE .

Some operating systems do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock. Whether the newly-acquired lock is shared or exclusive may be tested by invoking the resulting lock object's isShared method.

File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.

Parameters
position The position at which the locked region is to start; must be non-negative
size The size of the locked region; must be non-negative, and the sum position + size must be non-negative
shared true to request a shared lock, false to request an exclusive lock
Return
A lock object representing the newly-acquired lock, or null if the lock could not be acquired because another program holds an overlapping lock
Throws
IllegalArgumentException If the preconditions on the parameters do not hold
ClosedChannelException If this channel is closed
OverlappingFileLockException If a lock that overlaps the requested region is already held by this Java virtual machine, or if another thread is already blocked in this method and is attempting to lock an overlapping region of the same file
IOException If some other I/O error occurs
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Writes a sequence of bytes to this channel from the given buffer.

Bytes are written starting at this channel's current file position unless the channel is in append mode, in which case the position is first advanced to the end of the file. The file is grown, if necessary, to accommodate the written bytes, and then the file position is updated with the number of bytes actually written. Otherwise this method behaves exactly as specified by the WritableByteChannel interface.

Writes a sequence of bytes to this channel from the given buffers.

An invocation of this method of the form c.write(srcs) behaves in exactly the same manner as the invocation

 c.write(srcs, 0, srcs.length);
Parameters
srcs The buffers from which bytes are to be retrieved
Return
The number of bytes written, possibly zero
Throws
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the write operation is in progress
ClosedByInterruptException If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt status
IOException If some other I/O error occurs
Writes a sequence of bytes to this channel from a subsequence of the given buffers.

An attempt is made to write up to r bytes to this channel, where r is the total number of bytes remaining in the specified subsequence of the given buffer array, that is,

 srcs[offset].remaining()
     + srcs[offset+1].remaining()
     + ... + srcs[offset+length-1].remaining()
at the moment that this method is invoked.

Suppose that a byte sequence of length n is written, where 0 <= n <= r. Up to the first srcs[offset].remaining() bytes of this sequence are written from buffer srcs[offset], up to the next srcs[offset+1].remaining() bytes are written from buffer srcs[offset+1], and so forth, until the entire byte sequence is written. As many bytes as possible are written from each buffer, hence the final position of each updated buffer, except the last updated buffer, is guaranteed to be equal to that buffer's limit.

Unless otherwise specified, a write operation will return only after writing all of the r requested bytes. Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.

This method may be invoked at any time. If another thread has already initiated a write operation upon this channel, however, then an invocation of this method will block until the first operation is complete.

Parameters
srcs The buffers from which bytes are to be retrieved
offset The offset within the buffer array of the first buffer from which bytes are to be retrieved; must be non-negative and no larger than srcs.length
length The maximum number of buffers to be accessed; must be non-negative and no larger than srcs.length - offset
Return
The number of bytes written, possibly zero
Throws
IndexOutOfBoundsException If the preconditions on the offset and length parameters do not hold
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the write operation is in progress
ClosedByInterruptException If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt status
IOException If some other I/O error occurs
Writes a sequence of bytes to this channel from the given buffer, starting at the given file position.

This method works in the same manner as the method, except that bytes are written starting at the given file position rather than at the channel's current position. This method does not modify this channel's position. If the given position is greater than the file's current size then the file will be grown to accommodate the new bytes; the values of any bytes between the previous end-of-file and the newly-written bytes are unspecified.

Parameters
src The buffer from which bytes are to be transferred
position The file position at which the transfer is to begin; must be non-negative
Return
The number of bytes written, possibly zero
Throws
IllegalArgumentException If the position is negative
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the write operation is in progress
ClosedByInterruptException If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt status
IOException If some other I/O error occurs