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