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