This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

Creates an unconnected socket, with the system-default type of SocketImpl.
@since
JDK1.1
@revised
1.4
Creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings.

If there is a security manager, its checkConnect method is called with the proxy host address and port number as its arguments. This could result in a SecurityException.

Examples:

  • Socket s = new Socket(Proxy.NO_PROXY); will create a plain socket ignoring any other proxy configuration.
  • Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080))); will create a socket connecting through the specified SOCKS proxy server.
Parameters
proxya {@link java.net.Proxy Proxy} object specifying what kind of proxying should be used.
Throws
IllegalArgumentExceptionif the proxy is of an invalid type or null.
SecurityExceptionif a security manager is present and permission to connect to the proxy is denied.
@since
1.5
Creates a stream socket and connects it to the specified port number on the named host.

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null). In other words, it is equivalent to specifying an address of the loopback interface.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters
hostthe host name, or null for the loopback address.
portthe port number.
Throws
UnknownHostExceptionif the IP address of the host could not be determined.
IOExceptionif an I/O error occurs when creating the socket.
SecurityExceptionif a security manager exists and its checkConnect method doesn't allow the operation.
Creates a stream socket and connects it to the specified port number at the specified IP address.

If the application has specified a socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters
addressthe IP address.
portthe port number.
Throws
IOExceptionif an I/O error occurs when creating the socket.
SecurityExceptionif a security manager exists and its checkConnect method doesn't allow the operation.
Creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied.

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null). In other words, it is equivalent to specifying an address of the loopback interface.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters
hostthe name of the remote host, or null for the loopback address.
portthe remote port
localAddrthe local address the socket is bound to
localPortthe local port the socket is bound to
Throws
IOExceptionif an I/O error occurs when creating the socket.
SecurityExceptionif a security manager exists and its checkConnect method doesn't allow the operation.
@since
JDK1.1
Creates a socket and connects it to the specified remote address on the specified remote port. The Socket will also bind() to the local address and port supplied.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters
addressthe remote address
portthe remote port
localAddrthe local address the socket is bound to
localPortthe local port the socket is bound to
Throws
IOExceptionif an I/O error occurs when creating the socket.
SecurityExceptionif a security manager exists and its checkConnect method doesn't allow the operation.
@since
JDK1.1
Creates a stream socket and connects it to the specified port number on the named host.

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null). In other words, it is equivalent to specifying an address of the loopback interface.

If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

If a UDP socket is used, TCP/IP related socket options will not apply.

Parameters
hostthe host name, or null for the loopback address.
portthe port number.
streama boolean indicating whether this is a stream socket or a datagram socket.
Throws
IOExceptionif an I/O error occurs when creating the socket.
SecurityExceptionif a security manager exists and its checkConnect method doesn't allow the operation.
@deprecated
Use DatagramSocket instead for UDP transport.
Creates a socket and connects it to the specified port number at the specified IP address.

If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with host.getHostAddress() and port as its arguments. This could result in a SecurityException.

If UDP socket is used, TCP/IP related socket options will not apply.

Parameters
hostthe IP address.
portthe port number.
streamif true, create a stream socket; otherwise, create a datagram socket.
Throws
IOExceptionif an I/O error occurs when creating the socket.
SecurityExceptionif a security manager exists and its checkConnect method doesn't allow the operation.
@deprecated
Use DatagramSocket instead for UDP transport.
Binds the socket to a local address.

If the address is null, then the system will pick up an ephemeral port and a valid local address to bind the socket.

Parameters
bindpointthe SocketAddress to bind to
Throws
IOExceptionif the bind operation fails, or if the socket is already bound.
IllegalArgumentExceptionif bindpoint is a SocketAddress subclass not supported by this socket
@since
1.4
See Also
Closes this socket.

Any thread currently blocked in an I/O operation upon this socket will throw a SocketException .

Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.

If this socket has an associated channel then the channel is closed as well.

Throws
IOExceptionif an I/O error occurs when closing this socket.
@revised
1.4
@spec
JSR-51
See Also
Connects this socket to the server.
Parameters
endpointthe SocketAddress
Throws
IOExceptionif an error occurs during the connection
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentExceptionif endpoint is null or is a SocketAddress subclass not supported by this socket
@since
1.4
@spec
JSR-51
Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.
Parameters
endpointthe SocketAddress
timeoutthe timeout value to be used in milliseconds.
Throws
IOExceptionif an error occurs during the connection
SocketTimeoutExceptionif timeout expires before connecting
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentExceptionif endpoint is null or is a SocketAddress subclass not supported by this socket
@since
1.4
@spec
JSR-51
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.
Returns the unique SocketChannel object associated with this socket, if any.

A socket will have a channel if, and only if, the channel itself was created via the SocketChannel.open or ServerSocketChannel.accept methods.

Return
the socket channel associated with this socket, or null if this socket was not created for a channel
@since
1.4
@spec
JSR-51
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 the address to which the socket is connected.
Return
the remote IP address to which this socket is connected, or null if the socket is not connected.
Returns an input stream for this socket.

If this socket has an associated channel then the resulting input stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the input stream's read operations will throw an java.nio.channels.IllegalBlockingModeException .

Under abnormal conditions the underlying connection may be broken by the remote host or the network software (for example a connection reset in the case of TCP connections). When a broken connection is detected by the network software the following applies to the returned input stream :-

  • The network software may discard bytes that are buffered by the socket. Bytes that aren't discarded by the network software can be read using read .

  • If there are no bytes buffered on the socket, or all buffered bytes have been consumed by read , then all subsequent calls to read will throw an IOException .

  • If there are no bytes buffered on the socket, and the socket has not been closed using close , then available will return 0.

Return
an input stream for reading bytes from this socket.
Throws
IOExceptionif an I/O error occurs when creating the input stream, the socket is closed, the socket is not connected, or the socket input has been shutdown using {@link #shutdownInput()}
@revised
1.4
@spec
JSR-51
Tests if SO_KEEPALIVE is enabled.
Return
a boolean indicating whether or not SO_KEEPALIVE is enabled.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.3
Gets the local address to which the socket is bound.
Return
the local address to which the socket is bound or InetAddress.anyLocalAddress() if the socket is not bound yet.
@since
JDK1.1
Returns the local port to which this socket is bound.
Return
the local port number to which this socket is bound or -1 if the socket is not bound yet.
Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.
Return
a SocketAddress representing the local endpoint of this socket, or null if it is not bound yet.
@since
1.4
Tests if OOBINLINE is enabled.
Return
a boolean indicating whether or not OOBINLINE is enabled.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.4
Returns an output stream for this socket.

If this socket has an associated channel then the resulting output stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the output stream's write operations will throw an java.nio.channels.IllegalBlockingModeException .

Return
an output stream for writing bytes to this socket.
Throws
IOExceptionif an I/O error occurs when creating the output stream or if the socket is not connected.
@revised
1.4
@spec
JSR-51
Returns the remote port to which this socket is connected.
Return
the remote port number to which this socket is connected, or 0 if the socket is not connected yet.
Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket.
Return
the value of the SO_RCVBUF option for this Socket.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.2
Returns the address of the endpoint this socket is connected to, or null if it is unconnected.
Return
a SocketAddress reprensenting the remote endpoint of this socket, or null if it is not connected yet.
@since
1.4
Tests if SO_REUSEADDR is enabled.
Return
a boolean indicating whether or not SO_REUSEADDR is enabled.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.4
Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket.
Return
the value of the SO_SNDBUF option for this Socket.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.2
Returns setting for SO_LINGER. -1 returns implies that the option is disabled. The setting only affects socket close.
Return
the setting for SO_LINGER.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
JDK1.1
Returns setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).
Return
the setting for SO_TIMEOUT
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
JDK1.1
Tests if TCP_NODELAY is enabled.
Return
a boolean indicating whether or not TCP_NODELAY is enabled.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
JDK1.1
Gets traffic class or type-of-service in the IP header for packets sent from this Socket

As the underlying network implementation may ignore the traffic class or type-of-service set using this method may return a different value than was previously set using the method on this Socket.

Return
the traffic class or type-of-service already set
Throws
SocketExceptionif there is an error obtaining the traffic class or type-of-service value.
@since
1.4
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.
Returns the binding state of the socket.
Return
true if the socket successfuly bound to an address
@since
1.4
See Also
Returns the closed state of the socket.
Return
true if the socket has been closed
@since
1.4
See Also
Returns the connection state of the socket.
Return
true if the socket successfuly connected to a server
@since
1.4
Returns whether the read-half of the socket connection is closed.
Return
true if the input of the socket has been shutdown
@since
1.4
Returns whether the write-half of the socket connection is closed.
Return
true if the output of the socket has been shutdown
@since
1.4
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.
Send one byte of urgent data on the socket. The byte to be sent is the lowest eight bits of the data parameter. The urgent byte is sent after any preceding writes to the socket OutputStream and before any future writes to the OutputStream.
Parameters
dataThe byte of data to send
Throws
IOExceptionif there is an error sending the data.
@since
1.4
Enable/disable SO_KEEPALIVE.
Parameters
onwhether or not to have socket keep alive turned on.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.3
Enable/disable OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded. If the user wishes to receive urgent data, then this option must be enabled. When enabled, urgent data is received inline with normal data.

Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between normal data and urgent data unless provided by a higher level protocol.

Parameters
ontrue to enable OOBINLINE, false to disable.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.4
Sets performance preferences for this socket.

Sockets use the TCP/IP protocol by default. Some implementations may offer alternative protocols which have different performance characteristics than TCP/IP. This method allows the application to express its own preferences as to how these tradeoffs should be made when the implementation chooses from the available protocols.

Performance preferences are described by three integers whose values indicate the relative importance of short connection time, low latency, and high bandwidth. The absolute values of the integers are irrelevant; in order to choose a protocol the values are simply compared, with larger values indicating stronger preferences. Negative values represent a lower priority than positive values. If the application prefers short connection time over both low latency and high bandwidth, for example, then it could invoke this method with the values (1, 0, 0). If the application prefers high bandwidth above low latency, and low latency above short connection time, then it could invoke this method with the values (0, 1, 2).

Invoking this method after this socket has been connected will have no effect.

Parameters
connectionTime An int expressing the relative importance of a short connection time
latency An int expressing the relative importance of low latency
bandwidth An int expressing the relative importance of high bandwidth
@since
1.5
Sets the SO_RCVBUF option to the specified value for this Socket. The SO_RCVBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

Increasing the receive buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.

Because SO_RCVBUF is a hint, applications that want to verify what size the buffers were set to should call .

The value of SO_RCVBUF is also used to set the TCP receive window that is advertized to the remote peer. Generally, the window size can be modified at any time when a socket is connected. However, if a receive window larger than 64K is required then this must be requested before the socket is connected to the remote peer. There are two cases to be aware of:

  1. For sockets accepted from a ServerSocket, this must be done by calling before the ServerSocket is bound to a local address.

  2. For client sockets, setReceiveBufferSize() must be called before connecting the socket to its remote peer.

Parameters
sizethe size to which to set the receive buffer size. This value must be greater than 0.
Throws
IllegalArgumentExceptionif the value is 0 or is negative.
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.2
Enable/disable the SO_REUSEADDR socket option.

When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.

Enabling SO_REUSEADDR prior to binding the socket using allows the socket to be bound even though a previous connection is in a timeout state.

When a Socket is created the initial setting of SO_REUSEADDR is disabled.

The behaviour when SO_REUSEADDR is enabled or disabled after a socket is bound (See ) is not defined.

Parameters
onwhether to enable or disable the socket option
Throws
SocketExceptionif an error occurs enabling or disabling the SO_RESUEADDR socket option, or the socket is closed.
@since
1.4
Sets the SO_SNDBUF option to the specified value for this Socket. The SO_SNDBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

Because SO_SNDBUF is a hint, applications that want to verify what size the buffers were set to should call .

Parameters
sizethe size to which to set the send buffer size. This value must be greater than 0.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
IllegalArgumentExceptionif the value is 0 or is negative.
@since
1.2
Sets the client socket implementation factory for the application. The factory can be specified only once.

When an application creates a new client socket, the socket implementation factory's createSocketImpl method is called to create the actual socket implementation.

Passing null to the method is a no-op unless the factory was already set.

If there is a security manager, this method first calls the security manager's checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.

Parameters
facthe desired factory.
Throws
IOExceptionif an I/O error occurs when setting the socket factory.
SocketExceptionif the factory is already defined.
SecurityExceptionif a security manager exists and its checkSetFactory method doesn't allow the operation.
Enable/disable SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. The setting only affects socket close.
Parameters
onwhether or not to linger on.
lingerhow long to linger for, if on is true.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
IllegalArgumentExceptionif the linger value is negative.
@since
JDK1.1
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
Parameters
timeoutthe specified timeout, in milliseconds.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
JDK 1.1
Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
Parameters
ontrue to enable TCP_NODELAY, false to disable.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
JDK1.1
Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket. As the underlying network implementation may ignore this value applications should consider it a hint.

The tc must be in the range 0 <= tc <= 255 or an IllegalArgumentException will be thrown.

Notes:

for Internet Protocol v4 the value consists of an octet with precedence and TOS fields as detailed in RFC 1349. The TOS field is bitset created by bitwise-or'ing values such the following :-

  • IPTOS_LOWCOST (0x02)
  • IPTOS_RELIABILITY (0x04)
  • IPTOS_THROUGHPUT (0x08)
  • IPTOS_LOWDELAY (0x10)
The last low order bit is always ignored as this corresponds to the MBZ (must be zero) bit.

Setting bits in the precedence field may result in a SocketException indicating that the operation is not permitted.

for Internet Protocol v6 tc is the value that would be placed into the sin6_flowinfo field of the IP header.

Parameters
tcan int value for the bitset.
Throws
SocketExceptionif there is an error setting the traffic class or type-of-service
@since
1.4
Places the input stream for this socket at "end of stream". Any data sent to the input stream side of the socket is acknowledged and then silently discarded.

If you read from a socket input stream after invoking shutdownInput() on the socket, the stream will return EOF.

Throws
IOExceptionif an I/O error occurs when shutting down this socket.
@since
1.3
Disables the output stream for this socket. For a TCP socket, any previously written data will be sent followed by TCP's normal connection termination sequence. If you write to a socket output stream after invoking shutdownOutput() on the socket, the stream will throw an IOException.
Throws
IOExceptionif an I/O error occurs when shutting down this socket.
@since
1.3
Converts this socket to a String.
Return
a string representation of this socket.
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.