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} and that
 193      * the return type of the {@code clone} method of an array type
 194      * {@code T[]} is {@code T[]}.
 195      * Otherwise, this method creates a new instance of the class of this
 196      * object and initializes all its fields with exactly the contents of
 197      * the corresponding fields of this object, as if by assignment; the
 198      * contents of the fields are not themselves cloned. Thus, this method
 199      * performs a "shallow copy" of this object, not a "deep copy" operation.
 200      * <p>
 201      * The class {@code Object} does not itself implement the interface
 202      * {@code Cloneable}, so calling the {@code clone} method on an object
 203      * whose class is {@code Object} will result in throwing an
 204      * exception at run time.
 205      *
 206      * @return     a clone of this instance.
 207      * @exception  CloneNotSupportedException  if the object's class does not
 208      *               support the {@code Cloneable} interface. Subclasses
 209      *               that override the {@code clone} method can also
 210      *               throw this exception to indicate that an instance cannot
 211      *               be cloned.
 212      * @see java.lang.Cloneable
 213      */
 214     protected native Object clone() throws CloneNotSupportedException;
 215 
 216     /**
 217      * Returns a string representation of the object. In general, the
 218      * {@code toString} method returns a string that
 219      * "textually represents" this object. The result should
 220      * be a concise but informative representation that is easy for a
 221      * person to read.
 222      * It is recommended that all subclasses override this method.
 223      * <p>
 224      * The {@code toString} method for class {@code Object}
 225      * returns a string consisting of the name of the class of which the
 226      * object is an instance, the at-sign character `{@code @}', and
 227      * the unsigned hexadecimal representation of the hash code of the
 228      * object. In other words, this method returns a string equal to the
 229      * value of:
 230      * <blockquote>
 231      * <pre>
 232      * getClass().getName() + '@' + Integer.toHexString(hashCode())
 233      * </pre></blockquote>
 234      *
 235      * @return  a string representation of the object.
 236      */
 237     public String toString() {
 238         return getClass().getName() + "@" + Integer.toHexString(hashCode());
 239     }
 240 
 241     /**
 242      * Wakes up a single thread that is waiting on this object's
 243      * monitor. If any threads are waiting on this object, one of them
 244      * is chosen to be awakened. The choice is arbitrary and occurs at
 245      * the discretion of the implementation. A thread waits on an object's
 246      * monitor by calling one of the {@code wait} methods.
 247      * <p>
 248      * The awakened thread will not be able to proceed until the current
 249      * thread relinquishes the lock on this object. The awakened thread will
 250      * compete in the usual manner with any other threads that might be
 251      * actively competing to synchronize on this object; for example, the
 252      * awakened thread enjoys no reliable privilege or disadvantage in being
 253      * the next thread to lock this object.
 254      * <p>
 255      * This method should only be called by a thread that is the owner
 256      * of this object's monitor. A thread becomes the owner of the
 257      * object's monitor in one of three ways:
 258      * <ul>
 259      * <li>By executing a synchronized instance method of that object.
 260      * <li>By executing the body of a {@code synchronized} statement
 261      *     that synchronizes on the object.
 262      * <li>For objects of type {@code Class,} by executing a
 263      *     synchronized static method of that class.
 264      * </ul>
 265      * <p>
 266      * Only one thread at a time can own an object's monitor.
 267      *
 268      * @exception  IllegalMonitorStateException  if the current thread is not
 269      *               the owner of this object's monitor.
 270      * @see        java.lang.Object#notifyAll()
 271      * @see        java.lang.Object#wait()
 272      */
 273     public final native void notify();
 274 
 275     /**
 276      * Wakes up all threads that are waiting on this object's monitor. A
 277      * thread waits on an object's monitor by calling one of the
 278      * {@code wait} methods.
 279      * <p>
 280      * The awakened threads will not be able to proceed until the current
 281      * thread relinquishes the lock on this object. The awakened threads
 282      * will compete in the usual manner with any other threads that might
 283      * be actively competing to synchronize on this object; for example,
 284      * the awakened threads enjoy no reliable privilege or disadvantage in
 285      * being the next thread to lock this object.
 286      * <p>
 287      * This method should only be called by a thread that is the owner
 288      * of this object's monitor. See the {@code notify} method for a
 289      * description of the ways in which a thread can become the owner of
 290      * a monitor.
 291      *
 292      * @exception  IllegalMonitorStateException  if the current thread is not
 293      *               the owner of this object's monitor.
 294      * @see        java.lang.Object#notify()
 295      * @see        java.lang.Object#wait()
 296      */
 297     public final native void notifyAll();
 298 
 299     /**
 300      * Causes the current thread to wait until either another thread invokes the
 301      * {@link java.lang.Object#notify()} method or the
 302      * {@link java.lang.Object#notifyAll()} method for this object, or a
 303      * specified amount of time has elapsed.
 304      * <p>
 305      * The current thread must own this object's monitor.
 306      * <p>
 307      * This method causes the current thread (call it <var>T</var>) to
 308      * place itself in the wait set for this object and then to relinquish
 309      * any and all synchronization claims on this object. Thread <var>T</var>
 310      * becomes disabled for thread scheduling purposes and lies dormant
 311      * until one of four things happens:
 312      * <ul>
 313      * <li>Some other thread invokes the {@code notify} method for this
 314      * object and thread <var>T</var> happens to be arbitrarily chosen as
 315      * the thread to be awakened.
 316      * <li>Some other thread invokes the {@code notifyAll} method for this
 317      * object.
 318      * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
 319      * thread <var>T</var>.
 320      * <li>The specified amount of real time has elapsed, more or less.  If
 321      * {@code timeout} is zero, however, then real time is not taken into
 322      * consideration and the thread simply waits until notified.
 323      * </ul>
 324      * The thread <var>T</var> is then removed from the wait set for this
 325      * object and re-enabled for thread scheduling. It then competes in the
 326      * usual manner with other threads for the right to synchronize on the
 327      * object; once it has gained control of the object, all its
 328      * synchronization claims on the object are restored to the status quo
 329      * ante - that is, to the situation as of the time that the {@code wait}
 330      * method was invoked. Thread <var>T</var> then returns from the
 331      * invocation of the {@code wait} method. Thus, on return from the
 332      * {@code wait} method, the synchronization state of the object and of
 333      * thread {@code T} is exactly as it was when the {@code wait} method
 334      * was invoked.
 335      * <p>
 336      * A thread can also wake up without being notified, interrupted, or
 337      * timing out, a so-called <i>spurious wakeup</i>.  While this will rarely
 338      * occur in practice, applications must guard against it by testing for
 339      * the condition that should have caused the thread to be awakened, and
 340      * continuing to wait if the condition is not satisfied.  In other words,
 341      * waits should always occur in loops, like this one:
 342      * <pre>
 343      *     synchronized (obj) {
 344      *         while (&lt;condition does not hold&gt;)
 345      *             obj.wait(timeout);
 346      *         ... // Perform action appropriate to condition
 347      *     }
 348      * </pre>
 349      * (For more information on this topic, see Section 3.2.3 in Doug Lea's
 350      * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
 351      * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
 352      * Language Guide" (Addison-Wesley, 2001).
 353      *
 354      * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
 355      * interrupted} by any thread before or while it is waiting, then an
 356      * {@code InterruptedException} is thrown.  This exception is not
 357      * thrown until the lock status of this object has been restored as
 358      * described above.
 359      *
 360      * <p>
 361      * Note that the {@code wait} method, as it places the current thread
 362      * into the wait set for this object, unlocks only this object; any
 363      * other objects on which the current thread may be synchronized remain
 364      * locked while the thread waits.
 365      * <p>
 366      * This method should only be called by a thread that is the owner
 367      * of this object's monitor. See the {@code notify} method for a
 368      * description of the ways in which a thread can become the owner of
 369      * a monitor.
 370      *
 371      * @param      timeout   the maximum time to wait in milliseconds.
 372      * @exception  IllegalArgumentException      if the value of timeout is
 373      *               negative.
 374      * @exception  IllegalMonitorStateException  if the current thread is not
 375      *               the owner of the object's monitor.
 376      * @exception  InterruptedException if any thread interrupted the
 377      *             current thread before or while the current thread
 378      *             was waiting for a notification.  The <i>interrupted
 379      *             status</i> of the current thread is cleared when
 380      *             this exception is thrown.
 381      * @see        java.lang.Object#notify()
 382      * @see        java.lang.Object#notifyAll()
 383      */
 384     public final native void wait(long timeout) throws InterruptedException;
 385 
 386     /**
 387      * Causes the current thread to wait until another thread invokes the
 388      * {@link java.lang.Object#notify()} method or the
 389      * {@link java.lang.Object#notifyAll()} method for this object, or
 390      * some other thread interrupts the current thread, or a certain
 391      * amount of real time has elapsed.
 392      * <p>
 393      * This method is similar to the {@code wait} method of one
 394      * argument, but it allows finer control over the amount of time to
 395      * wait for a notification before giving up. The amount of real time,
 396      * measured in nanoseconds, is given by:
 397      * <blockquote>
 398      * <pre>
 399      * 1000000*timeout+nanos</pre></blockquote>
 400      * <p>
 401      * In all other respects, this method does the same thing as the
 402      * method {@link #wait(long)} of one argument. In particular,
 403      * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
 404      * <p>
 405      * The current thread must own this object's monitor. The thread
 406      * releases ownership of this monitor and waits until either of the
 407      * following two conditions has occurred:
 408      * <ul>
 409      * <li>Another thread notifies threads waiting on this object's monitor
 410      *     to wake up either through a call to the {@code notify} method
 411      *     or the {@code notifyAll} method.
 412      * <li>The timeout period, specified by {@code timeout}
 413      *     milliseconds plus {@code nanos} nanoseconds arguments, has
 414      *     elapsed.
 415      * </ul>
 416      * <p>
 417      * The thread then waits until it can re-obtain ownership of the
 418      * monitor and resumes execution.
 419      * <p>
 420      * As in the one argument version, interrupts and spurious wakeups are
 421      * possible, and this method should always be used in a loop:
 422      * <pre>
 423      *     synchronized (obj) {
 424      *         while (&lt;condition does not hold&gt;)
 425      *             obj.wait(timeout, nanos);
 426      *         ... // Perform action appropriate to condition
 427      *     }
 428      * </pre>
 429      * This method should only be called by a thread that is the owner
 430      * of this object's monitor. See the {@code notify} method for a
 431      * description of the ways in which a thread can become the owner of
 432      * a monitor.
 433      *
 434      * @param      timeout   the maximum time to wait in milliseconds.
 435      * @param      nanos      additional time, in nanoseconds range
 436      *                       0-999999.
 437      * @exception  IllegalArgumentException      if the value of timeout is
 438      *                      negative or the value of nanos is
 439      *                      not in the range 0-999999.
 440      * @exception  IllegalMonitorStateException  if the current thread is not
 441      *               the owner of this object's monitor.
 442      * @exception  InterruptedException if any thread interrupted the
 443      *             current thread before or while the current thread
 444      *             was waiting for a notification.  The <i>interrupted
 445      *             status</i> of the current thread is cleared when
 446      *             this exception is thrown.
 447      */
 448     public final void wait(long timeout, int nanos) throws InterruptedException {
 449         if (timeout < 0) {
 450             throw new IllegalArgumentException("timeout value is negative");
 451         }
 452 
 453         if (nanos < 0 || nanos > 999999) {
 454             throw new IllegalArgumentException(
 455                                 "nanosecond timeout value out of range");
 456         }
 457 
 458         if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
 459             timeout++;
 460         }
 461 
 462         wait(timeout);
 463     }
 464 
 465     /**
 466      * Causes the current thread to wait until another thread invokes the
 467      * {@link java.lang.Object#notify()} method or the
 468      * {@link java.lang.Object#notifyAll()} method for this object.
 469      * In other words, this method behaves exactly as if it simply
 470      * performs the call {@code wait(0)}.
 471      * <p>
 472      * The current thread must own this object's monitor. The thread
 473      * releases ownership of this monitor and waits until another thread
 474      * notifies threads waiting on this object's monitor to wake up
 475      * either through a call to the {@code notify} method or the
 476      * {@code notifyAll} method. The thread then waits until it can
 477      * re-obtain ownership of the monitor and resumes execution.
 478      * <p>
 479      * As in the one argument version, interrupts and spurious wakeups are
 480      * possible, and this method should always be used in a loop:
 481      * <pre>
 482      *     synchronized (obj) {
 483      *         while (&lt;condition does not hold&gt;)
 484      *             obj.wait();
 485      *         ... // Perform action appropriate to condition
 486      *     }
 487      * </pre>
 488      * This method should only be called by a thread that is the owner
 489      * of this object's monitor. See the {@code notify} method for a
 490      * description of the ways in which a thread can become the owner of
 491      * a monitor.
 492      *
 493      * @exception  IllegalMonitorStateException  if the current thread is not
 494      *               the owner of the object's monitor.
 495      * @exception  InterruptedException if any thread interrupted the
 496      *             current thread before or while the current thread
 497      *             was waiting for a notification.  The <i>interrupted
 498      *             status</i> of the current thread is cleared when
 499      *             this exception is thrown.
 500      * @see        java.lang.Object#notify()
 501      * @see        java.lang.Object#notifyAll()
 502      */
 503     public final void wait() throws InterruptedException {
 504         wait(0);
 505     }
 506 
 507     /**
 508      * Called by the garbage collector on an object when garbage collection
 509      * determines that there are no more references to the object.
 510      * A subclass overrides the {@code finalize} method to dispose of
 511      * system resources or to perform other cleanup.
 512      * <p>
 513      * The general contract of {@code finalize} is that it is invoked
 514      * if and when the Java<font size="-2"><sup>TM</sup></font> virtual
 515      * machine has determined that there is no longer any
 516      * means by which this object can be accessed by any thread that has
 517      * not yet died, except as a result of an action taken by the
 518      * finalization of some other object or class which is ready to be
 519      * finalized. The {@code finalize} method may take any action, including
 520      * making this object available again to other threads; the usual purpose
 521      * of {@code finalize}, however, is to perform cleanup actions before
 522      * the object is irrevocably discarded. For example, the finalize method
 523      * for an object that represents an input/output connection might perform
 524      * explicit I/O transactions to break the connection before the object is
 525      * permanently discarded.
 526      * <p>
 527      * The {@code finalize} method of class {@code Object} performs no
 528      * special action; it simply returns normally. Subclasses of
 529      * {@code Object} may override this definition.
 530      * <p>
 531      * The Java programming language does not guarantee which thread will
 532      * invoke the {@code finalize} method for any given object. It is
 533      * guaranteed, however, that the thread that invokes finalize will not
 534      * be holding any user-visible synchronization locks when finalize is
 535      * invoked. If an uncaught exception is thrown by the finalize method,
 536      * the exception is ignored and finalization of that object terminates.
 537      * <p>
 538      * After the {@code finalize} method has been invoked for an object, no
 539      * further action is taken until the Java virtual machine has again
 540      * determined that there is no longer any means by which this object can
 541      * be accessed by any thread that has not yet died, including possible
 542      * actions by other objects or classes which are ready to be finalized,
 543      * at which point the object may be discarded.
 544      * <p>
 545      * The {@code finalize} method is never invoked more than once by a Java
 546      * virtual machine for any given object.
 547      * <p>
 548      * Any exception thrown by the {@code finalize} method causes
 549      * the finalization of this object to be halted, but is otherwise
 550      * ignored.
 551      *
 552      * @throws Throwable the {@code Exception} raised by this method
 553      */
 554     protected void finalize() throws Throwable { }
 555 }