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