The multicast datagram socket class is useful for sending and receiving IP multicast packets. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining "groups" of other multicast hosts on the internet.

A multicast group is specified by a class D IP address and by a standard UDP port number. Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive. The address 224.0.0.0 is reserved and should not be used.

One would join a multicast group by first creating a MulticastSocket with the desired port, then invoking the joinGroup(InetAddress groupAddr) method:

 // join a Multicast group and send the group salutations
 ...
 String msg = "Hello";
 InetAddress group = InetAddress.getByName("228.5.6.7");
 MulticastSocket s = new MulticastSocket(6789);
 s.joinGroup(group);
 DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),
                             group, 6789);
 s.send(hi);
 // get their responses!
 byte[] buf = new byte[1000];
 DatagramPacket recv = new DatagramPacket(buf, buf.length);
 s.receive(recv);
 ...
 // OK, I'm done talking - leave the group...
 s.leaveGroup(group);
 
When one sends a message to a multicast group, all subscribing recipients to that host and port receive the message (within the time-to-live range of the packet, see below). The socket needn't be a member of the multicast group to send messages to it.

When a socket subscribes to a multicast group/port, it receives datagrams sent by other hosts to the group/port, as do all other members of the group and port. A socket relinquishes membership in a group by the leaveGroup(InetAddress addr) method. Multiple MulticastSocket's may subscribe to a multicast group and port concurrently, and they will all receive group datagrams.

Currently applets are not allowed to use multicast sockets.

@author
Pavani Diwanji
@since
JDK1.1
Create a multicast socket.

If there is a security manager, its checkListen method is first called with 0 as its argument to ensure the operation is allowed. This could result in a SecurityException.

When the socket is created the method is called to enable the SO_REUSEADDR socket option.

Throws
IOExceptionif an I/O exception occurs while creating the MulticastSocket
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
Create a multicast socket and bind it to a specific port.

If there is a security manager, its checkListen method is first called with the port argument as its argument to ensure the operation is allowed. This could result in a SecurityException.

When the socket is created the method is called to enable the SO_REUSEADDR socket option.

Parameters
portport to use
Throws
IOExceptionif an I/O exception occurs while creating the MulticastSocket
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
Create a MulticastSocket bound to the specified socket address.

Or, if the address is null, create an unbound socket.

If there is a security manager, its checkListen method is first called with the SocketAddress port as its argument to ensure the operation is allowed. This could result in a SecurityException.

When the socket is created the method is called to enable the SO_REUSEADDR socket option.

Parameters
bindaddrSocket address to bind to, or null for an unbound socket.
Throws
IOExceptionif an I/O exception occurs while creating the MulticastSocket
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
@since
1.4
Binds this DatagramSocket to a specific address & port.

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

Parameters
addrThe address & port to bind to.
Throws
SocketExceptionif any error happens during the bind, or if the socket is already bound.
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
IllegalArgumentExceptionif addr is a SocketAddress subclass not supported by this socket.
@since
1.4
Closes this datagram socket.

Any thread currently blocked in {#link receive} upon this socket will throw a SocketException .

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

@revised
1.4
@spec
JSR-51
Connects the socket to a remote address for this socket. When a socket is connected to a remote address, packets may only be sent to or received from that address. By default a datagram socket is not connected.

If the remote destination to which the socket is connected does not exist, or is otherwise unreachable, and if an ICMP destination unreachable packet has been received for that address, then a subsequent call to send or receive may throw a PortUnreachableException. Note, there is no guarantee that the exception will be thrown.

A caller's permission to send and receive datagrams to a given host and port are checked at connect time. When a socket is connected, receive and send will not perform any security checks on incoming and outgoing packets, other than matching the packet's and the socket's address and port. On a send operation, if the packet's address is set and the packet's address and the socket's address do not match, an IllegalArgumentException will be thrown. A socket connected to a multicast address may only be used to send packets.

Parameters
addressthe remote address for the socket
portthe remote port for the socket.
Throws
IllegalArgumentExceptionif the address is null, or the port is out of range.
SecurityExceptionif the caller is not allowed to send datagrams to and receive datagrams from the address and port.
Connects this socket to a remote socket address (IP address + port number).

Parameters
addrThe remote address.
Throws
SocketExceptionif the connect fails
IllegalArgumentExceptionif addr is null or addr is a SocketAddress subclass not supported by this socket
@since
1.4
See Also
Disconnects the socket. This does nothing if the socket is not connected.
See Also
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.
Tests if SO_BROADCAST is enabled.
Return
a boolean indicating whether or not SO_BROADCAST is enabled.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
@since
1.4
Returns the unique java.nio.channels.DatagramChannel object associated with this datagram socket, if any.

A datagram socket will have a channel if, and only if, the channel itself was created via the DatagramChannel.open method.

Return
the datagram channel associated with this datagram 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 this socket is connected. Returns null if the socket is not connected.
Return
the address to which this socket is connected.
Retrieve the address of the network interface used for multicast packets.
Return
An InetAddress representing the address of the network interface used for multicast packets.
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
Gets the local address to which the socket is bound.

If there is a security manager, its checkConnect method is first called with the host address and -1 as its arguments to see if the operation is allowed.

Return
the local address to which the socket is bound, or an InetAddress representing any local address if either the socket is not bound, or the security manager checkConnect method does not allow the operation
@since
1.1
Returns the port number on the local host to which this socket is bound.
Return
the port number on the local host to which this socket is bound.
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
Get the setting for local loopback of multicast datagrams.
Return
true if the LoopbackMode has been disabled
Throws
SocketExceptionif an error occurs while getting the value
@since
1.4
Get the multicast network interface set.
Return
the multicast NetworkInterface currently set
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.4
Returns the port for this socket. Returns -1 if the socket is not connected.
Return
the port to which this socket is connected.
Get value of the SO_RCVBUF option for this DatagramSocket, that is the buffer size used by the platform for input on this DatagramSocket.
Return
the value of the SO_RCVBUF option for this DatagramSocket
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
Returns the address of the endpoint this socket is connected to, or null if it is unconnected.
Return
a SocketAddress representing 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 an UDP error.
@since
1.4
Get value of the SO_SNDBUF option for this DatagramSocket, that is the buffer size used by the platform for output on this DatagramSocket.
Return
the value of the SO_SNDBUF option for this DatagramSocket
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
Retrive 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 an UDP error.
@since
JDK1.1
Get the default time-to-live for multicast packets sent out on the socket.
Return
the default time-to-live value
Throws
IOExceptionif an I/O exception occurs while getting the default time-to-live value
Gets traffic class or type-of-service in the IP datagram header for packets sent from this DatagramSocket.

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 DatagramSocket.

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
Get the default time-to-live for multicast packets sent out on the socket.
Return
the default time-to-live value
Throws
IOExceptionif an I/O exception occurs while getting the default time-to-live value
@deprecated
use the getTimeToLive method instead, which returns an int instead of a byte.
See Also
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 succesfuly bound to an address
@since
1.4
Returns whether the socket is closed or not.
Return
true if the socket has been closed
@since
1.4
Returns the connection state of the socket.
Return
true if the socket succesfuly connected to a server
@since
1.4
Joins a multicast group. Its behavior may be affected by setInterface or setNetworkInterface.

If there is a security manager, this method first calls its checkMulticast method with the mcastaddr argument as its argument.

Parameters
mcastaddris the multicast address to join
Throws
IOExceptionif there is an error joining or when the address is not a multicast address.
SecurityExceptionif a security manager exists and its checkMulticast method doesn't allow the join.
Joins the specified multicast group at the specified interface.

If there is a security manager, this method first calls its checkMulticast method with the mcastaddr argument as its argument.

Parameters
mcastaddris the multicast address to join
netIfspecifies the local interface to receive multicast datagram packets, or null to defer to the interface set by {@link MulticastSocket#setInterface(InetAddress)} or {@link MulticastSocket#setNetworkInterface(NetworkInterface)}
Throws
IOExceptionif there is an error joining or when the address is not a multicast address.
SecurityExceptionif a security manager exists and its checkMulticast method doesn't allow the join.
IllegalArgumentExceptionif mcastaddr is null or is a SocketAddress subclass not supported by this socket
@since
1.4
Leave a multicast group. Its behavior may be affected by setInterface or setNetworkInterface.

If there is a security manager, this method first calls its checkMulticast method with the mcastaddr argument as its argument.

Parameters
mcastaddris the multicast address to leave
Throws
IOExceptionif there is an error leaving or when the address is not a multicast address.
SecurityExceptionif a security manager exists and its checkMulticast method doesn't allow the operation.
Leave a multicast group on a specified local interface.

If there is a security manager, this method first calls its checkMulticast method with the mcastaddr argument as its argument.

Parameters
mcastaddris the multicast address to leave
netIfspecifies the local interface or null to defer to the interface set by {@link MulticastSocket#setInterface(InetAddress)} or {@link MulticastSocket#setNetworkInterface(NetworkInterface)}
Throws
IOExceptionif there is an error leaving or when the address is not a multicast address.
SecurityExceptionif a security manager exists and its checkMulticast method doesn't allow the operation.
IllegalArgumentExceptionif mcastaddr is null or is a SocketAddress subclass not supported by this socket
@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.
Receives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine.

This method blocks until a datagram is received. The length field of the datagram packet object contains the length of the received message. If the message is longer than the packet's length, the message is truncated.

If there is a security manager, a packet cannot be received if the security manager's checkAccept method does not allow it.

Parameters
pthe DatagramPacket into which to place the incoming data.
Throws
IOExceptionif an I/O error occurs.
SocketTimeoutExceptionif setSoTimeout was previously called and the timeout has expired.
PortUnreachableExceptionmay be thrown if the socket is connected to a currently unreachable destination. Note, there is no guarantee that the exception will be thrown.
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode.
@revised
1.4
@spec
JSR-51
Sends a datagram packet from this socket. The DatagramPacket includes information indicating the data to be sent, its length, the IP address of the remote host, and the port number on the remote host.

If there is a security manager, and the socket is not currently connected to a remote address, this method first performs some security checks. First, if p.getAddress().isMulticastAddress() is true, this method calls the security manager's checkMulticast method with p.getAddress() as its argument. If the evaluation of that expression is false, this method instead calls the security manager's checkConnect method with arguments p.getAddress().getHostAddress() and p.getPort(). Each call to a security manager method could result in a SecurityException if the operation is not allowed.

Parameters
pthe DatagramPacket to be sent.
Throws
IOExceptionif an I/O error occurs.
SecurityExceptionif a security manager exists and its checkMulticast or checkConnect method doesn't allow the send.
PortUnreachableExceptionmay be thrown if the socket is connected to a currently unreachable destination. Note, there is no guarantee that the exception will be thrown.
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode.
@revised
1.4
@spec
JSR-51
Sends a datagram packet to the destination, with a TTL (time- to-live) other than the default for the socket. This method need only be used in instances where a particular TTL is desired; otherwise it is preferable to set a TTL once on the socket, and use that default TTL for all packets. This method does not alter the default TTL for the socket. Its behavior may be affected by setInterface.

If there is a security manager, this method first performs some security checks. First, if p.getAddress().isMulticastAddress() is true, this method calls the security manager's checkMulticast method with p.getAddress() and ttl as its arguments. If the evaluation of that expression is false, this method instead calls the security manager's checkConnect method with arguments p.getAddress().getHostAddress() and p.getPort(). Each call to a security manager method could result in a SecurityException if the operation is not allowed.

Parameters
pis the packet to be sent. The packet should contain the destination multicast ip address and the data to be sent. One does not need to be the member of the group to send packets to a destination multicast address.
ttloptional time to live for multicast packet. default ttl is 1.
Throws
IOExceptionis raised if an error occurs i.e error while setting ttl.
SecurityExceptionif a security manager exists and its checkMulticast or checkConnect method doesn't allow the send.
@deprecated
Use the following code or its equivalent instead: ...... int ttl = mcastSocket.getTimeToLive(); mcastSocket.setTimeToLive(newttl); mcastSocket.send(p); mcastSocket.setTimeToLive(ttl); ......
Enable/disable SO_BROADCAST.
Parameters
onwhether or not to have broadcast turned on.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
@since
1.4
Sets the datagram socket implementation factory for the application. The factory can be specified only once.

When an application creates a new datagram socket, the socket implementation factory's createDatagramSocketImpl method is called to create the actual datagram 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 datagram socket factory.
SocketExceptionif the factory is already defined.
SecurityExceptionif a security manager exists and its checkSetFactory method doesn't allow the operation.
Set the multicast network interface used by methods whose behavior would be affected by the value of the network interface. Useful for multihomed hosts.
Parameters
infthe InetAddress
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
Disable/Enable local loopback of multicast datagrams The option is used by the platform's networking code as a hint for setting whether multicast data will be looped back to the local socket.

Because this option is a hint, applications that want to verify what loopback mode is set to should call

Parameters
disabletrue to disable the LoopbackMode
Throws
SocketExceptionif an error occurs while setting the value
@since
1.4
Specify the network interface for outgoing multicast datagrams sent on this socket.
Parameters
netIfthe interface
Throws
SocketExceptionif there is an error in the underlying protocol, such as a TCP error.
@since
1.4
Sets the SO_RCVBUF option to the specified value for this DatagramSocket. The SO_RCVBUF option is used by the the network implementation as a hint to size the underlying network I/O buffers. The SO_RCVBUF setting may also be used by the network implementation to determine the maximum size of the packet that can be received on this socket.

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

Increasing SO_RCVBUF may allow the network implementation to buffer multiple packets when packets arrive faster than are being received using .

Note: It is implementation specific if a packet larger than SO_RCVBUF can be received.

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

For UDP sockets it may be necessary to bind more than one socket to the same socket address. This is typically for the purpose of receiving multicast packets (See java.net.MulticastSocket ). The SO_REUSEADDR socket option allows multiple sockets to be bound to the same socket address if the SO_REUSEADDR socket option is enabled prior to binding the socket using .

When a DatagramSocket 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
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 DatagramSocket. The SO_SNDBUF option is used by the network implementation as a hint to size the underlying network I/O buffers. The SO_SNDBUF setting may also be used by the network implementation to determine the maximum size of the packet that can be sent on this socket.

As SO_SNDBUF is a hint, applications that want to verify what size the buffer is should call .

Increasing the buffer size may allow multiple outgoing packets to be queued by the network implementation when the send rate is high.

Note: If is used to send a DatagramPacket that is larger than the setting of SO_SNDBUF then it is implementation specific if the packet is sent or discarded.

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 an UDP error.
IllegalArgumentExceptionif the value is 0 or is negative.
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a call to receive() for this DatagramSocket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the DatagramSocket 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 an UDP error.
@since
JDK1.1
Set the default time-to-live for multicast packets sent out on this MulticastSocket in order to control the scope of the multicasts.

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

Parameters
ttlthe time-to-live
Throws
IOExceptionif an I/O exception occurs while setting the default time-to-live value
Sets traffic class or type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket. 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
Set the default time-to-live for multicast packets sent out on this MulticastSocket in order to control the scope of the multicasts.

The ttl is an unsigned 8-bit quantity, and so must be in the range 0 <= ttl <= 0xFF .

Parameters
ttlthe time-to-live
Throws
IOExceptionif an I/O exception occurs while setting the default time-to-live value
@deprecated
use the setTimeToLive method instead, which uses int instead of byte as the type for ttl.
See Also
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.
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.