1 /*
   2  * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 /**
  29  * Class {@code Object} is the root of the class hierarchy.
  30  * Every class has {@code Object} as a superclass. All objects,
  31  * including arrays, implement the methods of this class.
  32  *
  33  * @author  unascribed
  34  * @see     java.lang.Class
  35  * @since   JDK1.0
  36  */
  37 public class Object {
  38 
  39     private static native void registerNatives();
  40     static {
  41         registerNatives();
  42     }
  43 
  44     /**
  45      * Returns the runtime class of this {@code Object}. The returned
  46      * {@code Class} object is the object that is locked by {@code
  47      * static synchronized} methods of the represented class.
  48      *
  49      * <p><b>The actual result type is {@code Class<? extends |X|>}
  50      * where {@code |X|} is the erasure of the static type of the
  51      * expression on which {@code getClass} is called.</b> For
  52      * example, no cast is required in this code fragment:</p>
  53      *
  54      * <p>
  55      * {@code Number n = 0;                             }<br>
  56      * {@code Class<? extends Number> c = n.getClass(); }
  57      * </p>
  58      *
  59      * @return The {@code Class} object that represents the runtime
  60      *         class of this object.
  61      * @see    <a href="http://java.sun.com/docs/books/jls/">The Java
  62      *         Language Specification, Third Edition (15.8.2 Class
  63      *         Literals)</a>
  64      */
  65     public final native Class<?> getClass();
  66 
  67     /**
  68      * Returns a hash code value for the object. This method is
  69      * supported for the benefit of hash tables such as those provided by
  70      * {@link java.util.HashMap}.
  71      * <p>
  72      * The general contract of {@code hashCode} is:
  73      * <ul>
  74      * <li>Whenever it is invoked on the same object more than once during
  75      *     an execution of a Java application, the {@code hashCode} method
  76      *     must consistently return the same integer, provided no information
  77      *     used in {@code equals} comparisons on the object is modified.
  78      *     This integer need not remain consistent from one execution of an
  79      *     application to another execution of the same application.
  80      * <li>If two objects are equal according to the {@code equals(Object)}
  81      *     method, then calling the {@code hashCode} method on each of
  82      *     the two objects must produce the same integer result.
  83      * <li>It is <em>not</em> required that if two objects are unequal
  84      *     according to the {@link java.lang.Object#equals(java.lang.Object)}
  85      *     method, then calling the {@code hashCode} method on each of the
  86      *     two objects must produce distinct integer results.  However, the
  87      *     programmer should be aware that producing distinct integer results
  88      *     for unequal objects may improve the performance of hash tables.
  89      * </ul>
  90      * <p>
  91      * As much as is reasonably practical, the hashCode method defined by
  92      * class {@code Object} does return distinct integers for distinct
  93      * objects. (This is typically implemented by converting the internal
  94      * address of the object into an integer, but this implementation
  95      * technique is not required by the
  96      * Java<font size="-2"><sup>TM</sup></font> programming language.)
  97      *
  98      * @return  a hash code value for this object.
  99      * @see     java.lang.Object#equals(java.lang.Object)
 100      * @see     java.lang.System#identityHashCode
 101      */
 102     public native int hashCode();
 103 
 104     /**
 105      * Indicates whether some other object is "equal to" this one.
 106      * <p>
 107      * The {@code equals} method implements an equivalence relation
 108      * on non-null object references:
 109      * <ul>
 110      * <li>It is <i>reflexive</i>: for any non-null reference value
 111      *     {@code x}, {@code x.equals(x)} should return
 112      *     {@code true}.
 113      * <li>It is <i>symmetric</i>: for any non-null reference values
 114      *     {@code x} and {@code y}, {@code x.equals(y)}
 115      *     should return {@code true} if and only if
 116      *     {@code y.equals(x)} returns {@code true}.
 117      * <li>It is <i>transitive</i>: for any non-null reference values
 118      *     {@code x}, {@code y}, and {@code z}, if
 119      *     {@code x.equals(y)} returns {@code true} and
 120      *     {@code y.equals(z)} returns {@code true}, then
 121      *     {@code x.equals(z)} should return {@code true}.
 122      * <li>It is <i>consistent</i>: for any non-null reference values
 123      *     {@code x} and {@code y}, multiple invocations of
 124      *     {@code x.equals(y)} consistently return {@code true}
 125      *     or consistently return {@code false}, provided no
 126      *     information used in {@code equals} comparisons on the
 127      *     objects is modified.
 128      * <li>For any non-null reference value {@code x},
 129      *     {@code x.equals(null)} should return {@code false}.
 130      * </ul>
 131      * <p>
 132      * The {@code equals} method for class {@code Object} implements
 133      * the most discriminating possible equivalence relation on objects;
 134      * that is, for any non-null reference values {@code x} and
 135      * {@code y}, this method returns {@code true} if and only
 136      * if {@code x} and {@code y} refer to the same object
 137      * ({@code x == y} has the value {@code true}).
 138      * <p>
 139      * Note that it is generally necessary to override the {@code hashCode}
 140      * method whenever this method is overridden, so as to maintain the
 141      * general contract for the {@code hashCode} method, which states
 142      * that equal objects must have equal hash codes.
 143      *
 144      * @param   obj   the reference object with which to compare.
 145      * @return  {@code true} if this object is the same as the obj
 146      *          argument; {@code false} otherwise.
 147      * @see     #hashCode()
 148      * @see     java.util.HashMap
 149      */
 150     public boolean equals(Object obj) {
 151         return (this == obj);
 152     }
 153 
 154     /**
 155      * Creates and returns a copy of this object.  The precise meaning
 156      * of "copy" may depend on the class of the object. The general
 157      * intent is that, for any object {@code x}, the expression:
 158      * <blockquote>
 159      * <pre>
 160      * x.clone() != x</pre></blockquote>
 161      * will be true, and that the expression:
 162      * <blockquote>
 163      * <pre>
 164      * x.clone().getClass() == x.getClass()</pre></blockquote>
 165      * will be {@code true}, but these are not absolute requirements.
 166      * While it is typically the case that:
 167      * <blockquote>
 168      * <pre>
 169      * x.clone().equals(x)</pre></blockquote>
 170      * will be {@code true}, this is not an absolute requirement.
 171      * <p>
 172      * By convention, the returned object should be obtained by calling
 173      * {@code super.clone}.  If a class and all of its superclasses (except
 174      * {@code Object}) obey this convention, it will be the case that
 175      * {@code x.clone().getClass() == x.getClass()}.
 176      * <p>
 177      * By convention, the object returned by this method should be independent
 178      * of this object (which is being cloned).  To achieve this independence,
 179      * it may be necessary to modify one or more fields of the object returned
 180      * by {@code super.clone} before returning it.  Typically, this means
 181      * copying any mutable objects that comprise the internal "deep structure"
 182      * of the object being cloned and replacing the references to these
 183      * objects with references to the copies.  If a class contains only
 184      * primitive fields or references to immutable objects, then it is usually
 185      * the case that no fields in the object returned by {@code super.clone}
 186      * need to be modified.
 187      * <p>
 188      * The method {@code clone} for class {@code Object} performs a
 189      * specific cloning operation. First, if the class of this object does
 190      * not implement the interface {@code Cloneable}, then a
 191      * {@code CloneNotSupportedException} is thrown. Note that all arrays
 192      * are considered to implement the interface {@code Cloneable}.
 193      * Otherwise, this method creates a new instance of the class of this
 194      * object and initializes all its fields with exactly the contents of
 195      * the corresponding fields of this object, as if by assignment; the
 196      * contents of the fields are not themselves cloned. Thus, this method
 197      * performs a "shallow copy" of this object, not a "deep copy" operation.
 198      * <p>
 199      * The class {@code Object} does not itself implement the interface
 200      * {@code Cloneable}, so calling the {@code clone} method on an object
 201      * whose class is {@code Object} will result in throwing an
 202      * exception at run time.
 203      *
 204      * @return     a clone of this instance.
 205      * @exception  CloneNotSupportedException  if the object's class does not
 206      *               support the {@code Cloneable} interface. Subclasses
 207      *               that override the {@code clone} method can also
 208      *               throw this exception to indicate that an instance cannot
 209      *               be cloned.
 210      * @see java.lang.Cloneable
 211      */
 212     protected native Object clone() throws CloneNotSupportedException;
 213 
 214     /**
 215      * Returns a string representation of the object. In general, the
 216      * {@code toString} method returns a string that
 217      * "textually represents" this object. The result should
 218      * be a concise but informative representation that is easy for a
 219      * person to read.
 220      * It is recommended that all subclasses override this method.
 221      * <p>
 222      * The {@code toString} method for class {@code Object}
 223      * returns a string consisting of the name of the class of which the
 224      * object is an instance, the at-sign character `{@code @}', and
 225      * the unsigned hexadecimal representation of the hash code of the
 226      * object. In other words, this method returns a string equal to the
 227      * value of:
 228      * <blockquote>
 229      * <pre>
 230      * getClass().getName() + '@' + Integer.toHexString(hashCode())
 231      * </pre></blockquote>
 232      *
 233      * @return  a string representation of the object.
 234      */
 235     public String toString() {
 236         return getClass().getName() + "@" + Integer.toHexString(hashCode());
 237     }
 238 
 239     /**
 240      * Wakes up a single thread that is waiting on this object's
 241      * monitor. If any threads are waiting on this object, one of them
 242      * is chosen to be awakened. The choice is arbitrary and occurs at
 243      * the discretion of the implementation. A thread waits on an object's
 244      * monitor by calling one of the {@code wait} methods.
 245      * <p>
 246      * The awakened thread will not be able to proceed until the current
 247      * thread relinquishes the lock on this object. The awakened thread will
 248      * compete in the usual manner with any other threads that might be
 249      * actively competing to synchronize on this object; for example, the
 250      * awakened thread enjoys no reliable privilege or disadvantage in being
 251      * the next thread to lock this object.
 252      * <p>
 253      * This method should only be called by a thread that is the owner
 254      * of this object's monitor. A thread becomes the owner of the
 255      * object's monitor in one of three ways:
 256      * <ul>
 257      * <li>By executing a synchronized instance method of that object.
 258      * <li>By executing the body of a {@code synchronized} statement
 259      *     that synchronizes on the object.
 260      * <li>For objects of type {@code Class,} by executing a
 261      *     synchronized static method of that class.
 262      * </ul>
 263      * <p>
 264      * Only one thread at a time can own an object's monitor.
 265      *
 266      * @exception  IllegalMonitorStateException  if the current thread is not
 267      *               the owner of this object's monitor.
 268      * @see        java.lang.Object#notifyAll()
 269      * @see        java.lang.Object#wait()
 270      */
 271     public final native void notify();
 272 
 273     /**
 274      * Wakes up all threads that are waiting on this object's monitor. A
 275      * thread waits on an object's monitor by calling one of the
 276      * {@code wait} methods.
 277      * <p>
 278      * The awakened threads will not be able to proceed until the current
 279      * thread relinquishes the lock on this object. The awakened threads
 280      * will compete in the usual manner with any other threads that might
 281      * be actively competing to synchronize on this object; for example,
 282      * the awakened threads enjoy no reliable privilege or disadvantage in
 283      * being the next thread to lock this object.
 284      * <p>
 285      * This method should only be called by a thread that is the owner
 286      * of this object's monitor. See the {@code notify} method for a
 287      * description of the ways in which a thread can become the owner of
 288      * a monitor.
 289      *
 290      * @exception  IllegalMonitorStateException  if the current thread is not
 291      *               the owner of this object's monitor.
 292      * @see        java.lang.Object#notify()
 293      * @see        java.lang.Object#wait()
 294      */
 295     public final native void notifyAll();
 296 
 297     /**
 298      * Causes the current thread to wait until either another thread invokes the
 299      * {@link java.lang.Object#notify()} method or the
 300      * {@link java.lang.Object#notifyAll()} method for this object, or a
 301      * specified amount of time has elapsed.
 302      * <p>
 303      * The current thread must own this object's monitor.
 304      * <p>
 305      * This method causes the current thread (call it <var>T</var>) to
 306      * place itself in the wait set for this object and then to relinquish
 307      * any and all synchronization claims on this object. Thread <var>T</var>
 308      * becomes disabled for thread scheduling purposes and lies dormant
 309      * until one of four things happens:
 310      * <ul>
 311      * <li>Some other thread invokes the {@code notify} method for this
 312      * object and thread <var>T</var> happens to be arbitrarily chosen as
 313      * the thread to be awakened.
 314      * <li>Some other thread invokes the {@code notifyAll} method for this
 315      * object.
 316      * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
 317      * thread <var>T</var>.
 318      * <li>The specified amount of real time has elapsed, more or less.  If
 319      * {@code timeout} is zero, however, then real time is not taken into
 320      * consideration and the thread simply waits until notified.
 321      * </ul>
 322      * The thread <var>T</var> is then removed from the wait set for this
 323      * object and re-enabled for thread scheduling. It then competes in the
 324      * usual manner with other threads for the right to synchronize on the
 325      * object; once it has gained control of the object, all its
 326      * synchronization claims on the object are restored to the status quo
 327      * ante - that is, to the situation as of the time that the {@code wait}
 328      * method was invoked. Thread <var>T</var> then returns from the
 329      * invocation of the {@code wait} method. Thus, on return from the
 330      * {@code wait} method, the synchronization state of the object and of
 331      * thread {@code T} is exactly as it was when the {@code wait} method
 332      * was invoked.
 333      * <p>
 334      * A thread can also wake up without being notified, interrupted, or
 335      * timing out, a so-called <i>spurious wakeup</i>.  While this will rarely
 336      * occur in practice, applications must guard against it by testing for
 337      * the condition that should have caused the thread to be awakened, and
 338      * continuing to wait if the condition is not satisfied.  In other words,
 339      * waits should always occur in loops, like this one:
 340      * <pre>
 341      *     synchronized (obj) {
 342      *         while (&lt;condition does not hold&gt;)
 343      *             obj.wait(timeout);
 344      *         ... // Perform action appropriate to condition
 345      *     }
 346      * </pre>
 347      * (For more information on this topic, see Section 3.2.3 in Doug Lea's
 348      * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
 349      * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
 350      * Language Guide" (Addison-Wesley, 2001).
 351      *
 352      * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
 353      * interrupted} by any thread before or while it is waiting, then an
 354      * {@code InterruptedException} is thrown.  This exception is not
 355      * thrown until the lock status of this object has been restored as
 356      * described above.
 357      *
 358      * <p>
 359      * Note that the {@code wait} method, as it places the current thread
 360      * into the wait set for this object, unlocks only this object; any
 361      * other objects on which the current thread may be synchronized remain
 362      * locked while the thread waits.
 363      * <p>
 364      * This method should only be called by a thread that is the owner
 365      * of this object's monitor. See the {@code notify} method for a
 366      * description of the ways in which a thread can become the owner of
 367      * a monitor.
 368      *
 369      * @param      timeout   the maximum time to wait in milliseconds.
 370      * @exception  IllegalArgumentException      if the value of timeout is
 371      *               negative.
 372      * @exception  IllegalMonitorStateException  if the current thread is not
 373      *               the owner of the object's monitor.
 374      * @exception  InterruptedException if any thread interrupted the
 375      *             current thread before or while the current thread
 376      *             was waiting for a notification.  The <i>interrupted
 377      *             status</i> of the current thread is cleared when
 378      *             this exception is thrown.
 379      * @see        java.lang.Object#notify()
 380      * @see        java.lang.Object#notifyAll()
 381      */
 382     public final native void wait(long timeout) throws InterruptedException;
 383 
 384     /**
 385      * Causes the current thread to wait until another thread invokes the
 386      * {@link java.lang.Object#notify()} method or the
 387      * {@link java.lang.Object#notifyAll()} method for this object, or
 388      * some other thread interrupts the current thread, or a certain
 389      * amount of real time has elapsed.
 390      * <p>
 391      * This method is similar to the {@code wait} method of one
 392      * argument, but it allows finer control over the amount of time to
 393      * wait for a notification before giving up. The amount of real time,
 394      * measured in nanoseconds, is given by:
 395      * <blockquote>
 396      * <pre>
 397      * 1000000*timeout+nanos</pre></blockquote>
 398      * <p>
 399      * In all other respects, this method does the same thing as the
 400      * method {@link #wait(long)} of one argument. In particular,
 401      * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
 402      * <p>
 403      * The current thread must own this object's monitor. The thread
 404      * releases ownership of this monitor and waits until either of the
 405      * following two conditions has occurred:
 406      * <ul>
 407      * <li>Another thread notifies threads waiting on this object's monitor
 408      *     to wake up either through a call to the {@code notify} method
 409      *     or the {@code notifyAll} method.
 410      * <li>The timeout period, specified by {@code timeout}
 411      *     milliseconds plus {@code nanos} nanoseconds arguments, has
 412      *     elapsed.
 413      * </ul>
 414      * <p>
 415      * The thread then waits until it can re-obtain ownership of the
 416      * monitor and resumes execution.
 417      * <p>
 418      * As in the one argument version, interrupts and spurious wakeups are
 419      * possible, and this method should always be used in a loop:
 420      * <pre>
 421      *     synchronized (obj) {
 422      *         while (&lt;condition does not hold&gt;)
 423      *             obj.wait(timeout, nanos);
 424      *         ... // Perform action appropriate to condition
 425      *     }
 426      * </pre>
 427      * This method should only be called by a thread that is the owner
 428      * of this object's monitor. See the {@code notify} method for a
 429      * description of the ways in which a thread can become the owner of
 430      * a monitor.
 431      *
 432      * @param      timeout   the maximum time to wait in milliseconds.
 433      * @param      nanos      additional time, in nanoseconds range
 434      *                       0-999999.
 435      * @exception  IllegalArgumentException      if the value of timeout is
 436      *                      negative or the value of nanos is
 437      *                      not in the range 0-999999.
 438      * @exception  IllegalMonitorStateException  if the current thread is not
 439      *               the owner of this object's monitor.
 440      * @exception  InterruptedException if any thread interrupted the
 441      *             current thread before or while the current thread
 442      *             was waiting for a notification.  The <i>interrupted
 443      *             status</i> of the current thread is cleared when
 444      *             this exception is thrown.
 445      */
 446     public final void wait(long timeout, int nanos) throws InterruptedException {
 447         if (timeout < 0) {
 448             throw new IllegalArgumentException("timeout value is negative");
 449         }
 450 
 451         if (nanos < 0 || nanos > 999999) {
 452             throw new IllegalArgumentException(
 453                                 "nanosecond timeout value out of range");
 454         }
 455 
 456         if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
 457             timeout++;
 458         }
 459 
 460         wait(timeout);
 461     }
 462 
 463     /**
 464      * Causes the current thread to wait until another thread invokes the
 465      * {@link java.lang.Object#notify()} method or the
 466      * {@link java.lang.Object#notifyAll()} method for this object.
 467      * In other words, this method behaves exactly as if it simply
 468      * performs the call {@code wait(0)}.
 469      * <p>
 470      * The current thread must own this object's monitor. The thread
 471      * releases ownership of this monitor and waits until another thread
 472      * notifies threads waiting on this object's monitor to wake up
 473      * either through a call to the {@code notify} method or the
 474      * {@code notifyAll} method. The thread then waits until it can
 475      * re-obtain ownership of the monitor and resumes execution.
 476      * <p>
 477      * As in the one argument version, interrupts and spurious wakeups are
 478      * possible, and this method should always be used in a loop:
 479      * <pre>
 480      *     synchronized (obj) {
 481      *         while (&lt;condition does not hold&gt;)
 482      *             obj.wait();
 483      *         ... // Perform action appropriate to condition
 484      *     }
 485      * </pre>
 486      * This method should only be called by a thread that is the owner
 487      * of this object's monitor. See the {@code notify} method for a
 488      * description of the ways in which a thread can become the owner of
 489      * a monitor.
 490      *
 491      * @exception  IllegalMonitorStateException  if the current thread is not
 492      *               the owner of the object's monitor.
 493      * @exception  InterruptedException if any thread interrupted the
 494      *             current thread before or while the current thread
 495      *             was waiting for a notification.  The <i>interrupted
 496      *             status</i> of the current thread is cleared when
 497      *             this exception is thrown.
 498      * @see        java.lang.Object#notify()
 499      * @see        java.lang.Object#notifyAll()
 500      */
 501     public final void wait() throws InterruptedException {
 502         wait(0);
 503     }
 504 
 505     /**
 506      * Called by the garbage collector on an object when garbage collection
 507      * determines that there are no more references to the object.
 508      * A subclass overrides the {@code finalize} method to dispose of
 509      * system resources or to perform other cleanup.
 510      * <p>
 511      * The general contract of {@code finalize} is that it is invoked
 512      * if and when the Java<font size="-2"><sup>TM</sup></font> virtual
 513      * machine has determined that there is no longer any
 514      * means by which this object can be accessed by any thread that has
 515      * not yet died, except as a result of an action taken by the
 516      * finalization of some other object or class which is ready to be
 517      * finalized. The {@code finalize} method may take any action, including
 518      * making this object available again to other threads; the usual purpose
 519      * of {@code finalize}, however, is to perform cleanup actions before
 520      * the object is irrevocably discarded. For example, the finalize method
 521      * for an object that represents an input/output connection might perform
 522      * explicit I/O transactions to break the connection before the object is
 523      * permanently discarded.
 524      * <p>
 525      * The {@code finalize} method of class {@code Object} performs no
 526      * special action; it simply returns normally. Subclasses of
 527      * {@code Object} may override this definition.
 528      * <p>
 529      * The Java programming language does not guarantee which thread will
 530      * invoke the {@code finalize} method for any given object. It is
 531      * guaranteed, however, that the thread that invokes finalize will not
 532      * be holding any user-visible synchronization locks when finalize is
 533      * invoked. If an uncaught exception is thrown by the finalize method,
 534      * the exception is ignored and finalization of that object terminates.
 535      * <p>
 536      * After the {@code finalize} method has been invoked for an object, no
 537      * further action is taken until the Java virtual machine has again
 538      * determined that there is no longer any means by which this object can
 539      * be accessed by any thread that has not yet died, including possible
 540      * actions by other objects or classes which are ready to be finalized,
 541      * at which point the object may be discarded.
 542      * <p>
 543      * The {@code finalize} method is never invoked more than once by a Java
 544      * virtual machine for any given object.
 545      * <p>
 546      * Any exception thrown by the {@code finalize} method causes
 547      * the finalization of this object to be halted, but is otherwise
 548      * ignored.
 549      *
 550      * @throws Throwable the {@code Exception} raised by this method
 551      */
 552     protected void finalize() throws Throwable { }
 553 }