The BufferedImage subclass describes an Image with an accessible buffer of image data. A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0). Any Raster used to construct a BufferedImage must therefore have minX=0 and minY=0.

This class relies on the data fetching and setting methods of Raster, and on the color characterization methods of ColorModel.

@version
10 Feb 1997
Constructs a BufferedImage of one of the predefined image types. The ColorSpace for the image is the default sRGB space.
Parameters
widthwidth of the created image
heightheight of the created image
imageTypetype of the created image
Constructs a BufferedImage of one of the predefined image types: TYPE_BYTE_BINARY or TYPE_BYTE_INDEXED.

If the image type is TYPE_BYTE_BINARY, the number of entries in the color model is used to determine whether the image should have 1, 2, or 4 bits per pixel. If the color model has 1 or 2 entries, the image will have 1 bit per pixel. If it has 3 or 4 entries, the image with have 2 bits per pixel. If it has between 5 and 16 entries, the image will have 4 bits per pixel. Otherwise, an IllegalArgumentException will be thrown.

Parameters
widthwidth of the created image
heightheight of the created image
imageTypetype of the created image
cmIndexColorModel of the created image
Throws
IllegalArgumentExceptionif the imageType is not TYPE_BYTE_BINARY or TYPE_BYTE_INDEXED or if the imageType is TYPE_BYTE_BINARY and the color map has more than 16 entries.
Constructs a new BufferedImage with a specified ColorModel and Raster. If the number and types of bands in the SampleModel of the Raster do not match the number and types required by the ColorModel to represent its color and alpha components, a RasterFormatException is thrown. This method can multiply or divide the color Raster data by alpha to match the alphaPremultiplied state in the ColorModel. Properties for this BufferedImage can be established by passing in a Hashtable of String/Object pairs.
Parameters
cmColorModel for the new image
rasterRaster for the image data
isRasterPremultipliedif true, the data in the raster has been premultiplied with alpha.
propertiesHashtable of String/Object pairs.
Throws
RasterFormatExceptionif the number and types of bands in the SampleModel of the Raster do not match the number and types required by the ColorModel to represent its color and alpha components.
IllegalArgumentExceptionif raster is incompatible with cm
Represents image data that is guaranteed to be either completely opaque, with an alpha value of 1.0, or completely transparent, with an alpha value of 0.0.
Represents image data that is guaranteed to be completely opaque, meaning that all pixels have an alpha value of 1.0.
Use the Area Averaging image scaling algorithm. The image object is free to substitute a different filter that performs the same algorithm yet integrates more efficiently into the image infrastructure supplied by the toolkit.
Use the default image-scaling algorithm.
@since
JDK1.1
Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.
@since
JDK1.1
Use the image scaling algorithm embodied in the ReplicateScaleFilter class. The Image object is free to substitute a different filter that performs the same algorithm yet integrates more efficiently into the imaging infrastructure supplied by the toolkit.
Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.
@since
JDK1.1
Represents image data that contains or might contain arbitrary alpha values between and including 0.0 and 1.0.
Represents an image with 8-bit RGB color components, corresponding to a Windows-style BGR color model) with the colors Blue, Green, and Red stored in 3 bytes. There is no alpha. The image has a ComponentColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
Represents an image with 8-bit RGBA color components with the colors Blue, Green, and Red stored in 3 bytes and 1 byte of alpha. The image has a ComponentColorModel with alpha. The color data in this image is considered not to be premultiplied with alpha. The byte data is interleaved in a single byte array in the order A, B, G, R from lower to higher byte addresses within each pixel.
Represents an image with 8-bit RGBA color components with the colors Blue, Green, and Red stored in 3 bytes and 1 byte of alpha. The image has a ComponentColorModel with alpha. The color data in this image is considered to be premultiplied with alpha. The byte data is interleaved in a single byte array in the order A, B, G, R from lower to higher byte addresses within each pixel.
Represents an opaque byte-packed 1, 2, or 4 bit image. The image has an IndexColorModel without alpha. When this type is used as the imageType argument to the BufferedImage constructor that takes an imageType argument but no ColorModel argument, a 1-bit image is created with an IndexColorModel with two colors in the default sRGB ColorSpace: {0, 0, 0} and {255, 255, 255}.

Images with 2 or 4 bits per pixel may be constructed via the BufferedImage constructor that takes a ColorModel argument by supplying a ColorModel with an appropriate map size.

Images with 8 bits per pixel should use the image types TYPE_BYTE_INDEXED or TYPE_BYTE_GRAY depending on their ColorModel.

When color data is stored in an image of this type, the closest color in the colormap is determined by the IndexColorModel and the resulting index is stored. Approximation and loss of alpha or color components can result, depending on the colors in the IndexColorModel colormap.

Represents a unsigned byte grayscale image, non-indexed. This image has a ComponentColorModel with a CS_GRAY ColorSpace . When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
Represents an indexed byte image. When this type is used as the imageType argument to the BufferedImage constructor that takes an imageType argument but no ColorModel argument, an IndexColorModel is created with a 256-color 6/6/6 color cube palette with the rest of the colors from 216-255 populated by grayscale values in the default sRGB ColorSpace.

When color data is stored in an image of this type, the closest color in the colormap is determined by the IndexColorModel and the resulting index is stored. Approximation and loss of alpha or color components can result, depending on the colors in the IndexColorModel colormap.

Image type is not recognized so it must be a customized image. This type is only used as a return value for the getType() method.
Represents an image with 8-bit RGBA color components packed into integer pixels. The image has a DirectColorModel with alpha. The color data in this image is considered not to be premultiplied with alpha. When this type is used as the imageType argument to a BufferedImage constructor, the created image is consistent with images created in the JDK1.1 and earlier releases.
Represents an image with 8-bit RGBA color components packed into integer pixels. The image has a DirectColorModel with alpha. The color data in this image is considered to be premultiplied with alpha.
Represents an image with 8-bit RGB color components, corresponding to a Windows- or Solaris- style BGR color model, with the colors Blue, Green, and Red packed into integer pixels. There is no alpha. The image has a DirectColorModel . When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
Represents an image with 8-bit RGB color components packed into integer pixels. The image has a DirectColorModel without alpha. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
Represents an image with 5-5-5 RGB color components (5-bits red, 5-bits green, 5-bits blue) with no alpha. This image has a DirectColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
Represents an image with 5-6-5 RGB color components (5-bits red, 6-bits green, 5-bits blue) with no alpha. This image has a DirectColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
Represents an unsigned short grayscale image, non-indexed). This image has a ComponentColorModel with a CS_GRAY ColorSpace. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the java.awt.AlphaComposite documentation.
The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.
Adds an observer. If the observer is already present, it will receive multiple notifications.
Parameters
tothe specified TileObserver
Forces the data to match the state specified in the isAlphaPremultiplied variable. It may multiply or divide the color raster data by alpha, or do nothing if the data is in the correct state.
Parameters
isAlphaPremultipliedtrue if the alpha has been premultiplied; false otherwise.
Computes an arbitrary rectangular region of the BufferedImage and copies it into a specified WritableRaster. The region to be computed is determined from the bounds of the specified WritableRaster. The specified WritableRaster must have a SampleModel that is compatible with this image. If outRaster is null, an appropriate WritableRaster is created.
Parameters
outRastera WritableRaster to hold the returned part of the image, or null
Return
a reference to the supplied or created WritableRaster.
Creates a Graphics2D, which can be used to draw into this BufferedImage.
Return
a Graphics2D, used for drawing into this image.
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.
Flushes all resources being used to cache optimization information. The underlying pixel data is unaffected.
Returns the current value of the acceleration priority hint.
Return
value between 0 and 1, inclusive, which represents the current priority value
@since
1.5
Returns a WritableRaster representing the alpha channel for BufferedImage objects with ColorModel objects that support a separate spatial alpha channel, such as ComponentColorModel and DirectColorModel. Returns null if there is no alpha channel associated with the ColorModel in this image. This method assumes that for all ColorModel objects other than IndexColorModel, if the ColorModel supports alpha, there is a separate alpha channel which is stored as the last band of image data. If the image uses an IndexColorModel that has alpha in the lookup table, this method returns null since there is no spatially discrete alpha channel. This method creates a new WritableRaster, but shares the data array.
Return
a WritableRaster or null if this BufferedImage has no alpha channel associated with its ColorModel.
This overrides Image.getCapabilities(gc) to get the capabilities of its surfaceManager. This means that BufferedImage objects that are accelerated may return a caps object that will indicate this acceleration.
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 ColorModel.
Return
the ColorModel of this BufferedImage.
Returns the image as one large tile. The Raster returned is a copy of the image data is not updated if the image is changed.
Return
a Raster that is a copy of the image data.
Computes and returns an arbitrary region of the BufferedImage. The Raster returned is a copy of the image data and is not updated if the image is changed.
Parameters
rectthe region of the BufferedImage to be returned.
Return
a Raster that is a copy of the image data of the specified region of the BufferedImage
This method returns a Graphics2D , but is here for backwards compatibility. createGraphics is more convenient, since it is declared to return a Graphics2D.
Return
a Graphics2D, which can be used to draw into this image.
Returns the height of the BufferedImage.
Return
the height of this BufferedImage
Returns the height of the BufferedImage.
Parameters
observerignored
Return
the height of this BufferedImage
Returns the minimum tile index in the x direction. This is always zero.
Return
the minimum tile index in the x direction.
Returns the minimum tile index in the y direction. This is always zero.
Return
the mininum tile index in the y direction.
Returns the minimum x coordinate of this BufferedImage. This is always zero.
Return
the minimum x coordinate of this BufferedImage.
Returns the minimum y coordinate of this BufferedImage. This is always zero.
Return
the minimum y coordinate of this BufferedImage.
Returns the number of tiles in the x direction. This is always one.
Return
the number of tiles in the x direction.
Returns the number of tiles in the y direction. This is always one.
Return
the number of tiles in the y direction.
Returns a property of the image by name.
Parameters
namethe property name
Return
an Object that is the property referred to by the specified name.
Throws
NullPointerExceptionif the property name is null.
Returns a property of the image by name. Individual property names are defined by the various image formats. If a property is not defined for a particular image, this method returns the UndefinedProperty field. If the properties for this image are not yet known, then this method returns null and the ImageObserver object is notified later. The property name "comment" should be used to store an optional comment that can be presented to the user as a description of the image, its source, or its author.
Parameters
namethe property name
observerthe ImageObserver that receives notification regarding image information
Return
an {@link Object} that is the property referred to by the specified name or null if the properties of this image are not yet known.
Throws
NullPointerExceptionif the property name is null.
Returns an array of names recognized by getProperty(String) or null, if no property names are recognized.
Return
a String array containing all of the property names that getProperty(String) recognizes; or null if no property names are recognized.
Returns the WritableRaster .
Return
the WriteableRaster of this BufferedImage.
Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace. Color conversion takes place if this default model does not match the image ColorModel. There are only 8-bits of precision for each color component in the returned data when using this method.

An ArrayOutOfBoundsException may be thrown if the coordinates are not in bounds. However, explicit bounds checking is not guaranteed.

Parameters
x, ythe coordinates of the pixel from which to get the pixel in the default RGB color model and sRGB color space
Return
an integer pixel in the default RGB color model and default sRGB colorspace.
Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data. Color conversion takes place if the default model does not match the image ColorModel. There are only 8-bits of precision for each color component in the returned data when using this method. With a specified coordinate (x, y) in the image, the ARGB pixel can be accessed in this way:

    pixel   = rgbArray[offset + (y-startY)*scansize + (x-startX)]; 

An ArrayOutOfBoundsException may be thrown if the region is not in bounds. However, explicit bounds checking is not guaranteed.

Parameters
startX, startYthe starting coordinates
wwidth of region
hheight of region
rgbArrayif not null, the rgb pixels are written here
offsetoffset into the rgbArray
scansizescanline stride for the rgbArray
Return
array of RGB pixels.
Returns the SampleModel associated with this BufferedImage.
Return
the SampleModel of this BufferedImage.
Creates a scaled version of this image. A new Image object is returned which will render the image at the specified width and height by default. The new Image object may be loaded asynchronously even if the original source image has already been loaded completely.

If either width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions. If both width and height are negative, then the original image dimensions are used.

Parameters
widththe width to which to scale the image.
heightthe height to which to scale the image.
hintsflags to indicate the type of algorithm to use for image resampling.
Return
a scaled version of the image.
Throws
IllegalArgumentExceptionif width or height is zero.
@since
JDK1.1
Returns the object that produces the pixels for the image.
Return
the {@link ImageProducer} that is used to produce the pixels for this image.
See Also
Returns a Vector of RenderedImage objects that are the immediate sources, not the sources of these immediate sources, of image data for this BufferedImage. This method returns null if the BufferedImage has no information about its immediate sources. It returns an empty Vector if the BufferedImage has no immediate sources.
Return
a Vector containing immediate sources of this BufferedImage object's image date, or null if this BufferedImage has no information about its immediate sources, or an empty Vector if this BufferedImage has no immediate sources.
Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.
Parameters
x, ythe coordinates of the upper-left corner of the specified rectangular region
wthe width of the specified rectangular region
hthe height of the specified rectangular region
Return
a BufferedImage that is the subimage of this BufferedImage.
Throws
RasterFormatExceptionif the specified area is not contained within this BufferedImage.
Returns tile (tileXtileY). Note that tileX and tileY are indices into the tile array, not pixel locations. The Raster that is returned is live, which means that it is updated if the image is changed.
Parameters
tileXthe x index of the requested tile in the tile array
tileYthe y index of the requested tile in the tile array
Return
a Raster that is the tile defined by the arguments tileX and tileY.
Throws
ArrayIndexOutOfBoundsExceptionif both tileX and tileY are not equal to 0
Returns the x offset of the tile grid relative to the origin, For example, the x coordinate of the location of tile (0, 0). This is always zero.
Return
the x offset of the tile grid.
Returns the y offset of the tile grid relative to the origin, For example, the y coordinate of the location of tile (0, 0). This is always zero.
Return
the y offset of the tile grid.
Returns the tile height in pixels.
Return
the tile height in pixels.
Returns the tile width in pixels.
Return
the tile width in pixels.
Returns the type of this Transparency.
Return
the field type of this Transparency, which is either OPAQUE, BITMASK or TRANSLUCENT.
Returns the image type. If it is not one of the known types, TYPE_CUSTOM is returned.
Returns the width of the BufferedImage.
Return
the width of this BufferedImage
Returns the width of the BufferedImage.
Parameters
observerignored
Return
the width of this BufferedImage
Checks out a tile for writing. The WritableRenderedImage is responsible for notifying all of its TileObservers when a tile goes from having no writers to having one writer.
Parameters
tileXthe X index of the tile.
tileYthe Y index of the tile.
Return
a writable tile.
Returns an array of Point objects indicating which tiles are checked out for writing. Returns null if none are checked out.
Return
an array containing the locations of tiles that are checked out for writing.
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 whether any tile is checked out for writing. Semantically equivalent to (getWritableTileIndices() != null).
Return
true if any tiles are checked out for writing; false otherwise.
Returns whether or not the alpha has been premultiplied. It returns false if there is no alpha.
Return
true if the alpha has been premultiplied; false otherwise.
Returns whether a tile is currently checked out for writing.
Parameters
tileXthe X index of the tile.
tileYthe Y index of the tile.
Return
true if specified tile is checked out for writing; false otherwise.
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.
Relinquishes the right to write to a tile. If the caller continues to write to the tile, the results are undefined. Calls to this method should only appear in matching pairs with calls to getWritableTile; any other use will lead to undefined results. The WritableRenderedImage is responsible for notifying all of its TileObservers when a tile goes from having one writer to having no writers.
Parameters
tileXthe X index of the tile.
tileYthe Y index of the tile.
Removes an observer. If the observer was not registered, nothing happens. If the observer was registered for multiple notifications, it will now be registered for one fewer.
Parameters
tothe specified TileObserver
Sets a hint for this image about how important acceleration is. This priority hint is used to compare to the priorities of other Image objects when determining how to use scarce acceleration resources such as video memory. When and if it is possible to accelerate this Image, if there are not enough resources available to provide that acceleration but enough can be freed up by de-acceleration some other image of lower priority, then that other Image may be de-accelerated in deference to this one. Images that have the same priority take up resources on a first-come, first-served basis.
Parameters
prioritya value between 0 and 1, inclusive, where higher values indicate more importance for acceleration. A value of 0 means that this Image should never be accelerated. Other values are used simply to determine acceleration priority relative to other Images.
Throws
IllegalArgumentExceptionif priority is less than zero or greater than 1.
@since
1.5
Sets a rect of the image to the contents of the Raster r, which is assumed to be in the same coordinate space as the WritableRenderedImage. The operation is clipped to the bounds of the WritableRenderedImage.
Parameters
rthe specified Raster
Sets a pixel in this BufferedImage to the specified RGB value. The pixel is assumed to be in the default RGB color model, TYPE_INT_ARGB, and default sRGB color space. For images with an IndexColorModel, the index with the nearest color is chosen.

An ArrayOutOfBoundsException may be thrown if the coordinates are not in bounds. However, explicit bounds checking is not guaranteed.

Parameters
x, ythe coordinates of the pixel to set
rgbthe RGB value
Sets an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, into a portion of the image data. Color conversion takes place if the default model does not match the image ColorModel. There are only 8-bits of precision for each color component in the returned data when using this method. With a specified coordinate (x, y) in the this image, the ARGB pixel can be accessed in this way:
    pixel   = rgbArray[offset + (y-startY)*scansize + (x-startX)];
 
WARNING: No dithering takes place.

An ArrayOutOfBoundsException may be thrown if the region is not in bounds. However, explicit bounds checking is not guaranteed.

Parameters
startX, startYthe starting coordinates
wwidth of the region
hheight of the region
rgbArraythe rgb pixels
offsetoffset into the rgbArray
scansizescanline stride for the rgbArray
Returns a String representation of this BufferedImage object and its values.
Return
a String representing this BufferedImage.
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.