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 
 30 /**
 31  * Class {@code Object} is the root of the class hierarchy.
 32  * Every class has {@code Object} as a superclass. All objects,
 33  * including arrays, implement the methods of this class.
 34  *
 35  * @see     java.lang.Class
 36  * @since   1.0
 37  */
 38 public class Object {
 39 
 40     /**
 41      * Constructs a new object.
 42      */
 43     @IntrinsicCandidate
 44     public Object() {}
 45 
 46     /**
 47      * Returns the runtime class of this {@code Object}. The returned
 48      * {@code Class} object is the object that is locked by {@code
 49      * static synchronized} methods of the represented class.
 50      *
 51      * <p><b>The actual result type is {@code Class<? extends |X|>}
 52      * where {@code |X|} is the erasure of the static type of the
 53      * expression on which {@code getClass} is called.</b> For
 54      * example, no cast is required in this code fragment:</p>
 55      *
 56      * <p>
 57      * {@code Number n = 0;                             }<br>
 58      * {@code Class<? extends Number> c = n.getClass(); }
 59      * </p>
 60      *
 61      * @return The {@code Class} object that represents the runtime
 62      *         class of this object.
 63      * @jls 15.8.2 Class Literals
 64      */
 65     @IntrinsicCandidate
 66     public final native Class<?> getClass();
 67 
 68     /**
 69      * Returns a hash code value for the object. This method is
 70      * supported for the benefit of hash tables such as those provided by
 71      * {@link java.util.HashMap}.
 72      * <p>
 73      * The general contract of {@code hashCode} is:
 74      * <ul>
 75      * <li>Whenever it is invoked on the same object more than once during
 76      *     an execution of a Java application, the {@code hashCode} method
 77      *     must consistently return the same integer, provided no information
 78      *     used in {@code equals} comparisons on the object is modified.
 79      *     This integer need not remain consistent from one execution of an
 80      *     application to another execution of the same application.
 81      * <li>If two objects are equal according to the {@link
 82      *     equals(Object) equals} method, then calling the {@code
 83      *     hashCode} method on each of the two objects must produce the
 84      *     same integer result.
 85      * <li>It is <em>not</em> required that if two objects are unequal
 86      *     according to the {@link equals(Object) equals} method, then
 87      *     calling the {@code hashCode} method on each of the two objects
 88      *     must produce distinct integer results.  However, the programmer
 89      *     should be aware that producing distinct integer results for
 90      *     unequal objects may improve the performance of hash tables.
 91      * </ul>
 92      *
 93      * @implSpec
 94      * As far as is reasonably practical, the {@code hashCode} method defined
 95      * by class {@code Object} returns distinct integers for distinct objects.
 96      *
 97      * @return  a hash code value for this object.
 98      * @see     java.lang.Object#equals(java.lang.Object)
 99      * @see     java.lang.System#identityHashCode
100      */
101     @IntrinsicCandidate
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      *
132      * <p>
133      * An equivalence relation partitions the elements it operates on
134      * into <i>equivalence classes</i>; all the members of an
135      * equivalence class are equal to each other. Members of an
136      * equivalence class are substitutable for each other, at least
137      * for some purposes.
138      *
139      * @implSpec
140      * The {@code equals} method for class {@code Object} implements
141      * the most discriminating possible equivalence relation on objects;
142      * that is, for any non-null reference values {@code x} and
143      * {@code y}, this method returns {@code true} if and only
144      * if {@code x} and {@code y} refer to the same object
145      * ({@code x == y} has the value {@code true}).
146      *
147      * In other words, under the reference equality equivalence
148      * relation, each equivalence class only has a single element.
149      *
150      * @apiNote
151      * It is generally necessary to override the {@link hashCode hashCode}
152      * method whenever this method is overridden, so as to maintain the
153      * general contract for the {@code hashCode} method, which states
154      * that equal objects must have equal hash codes.
155      *
156      * @param   obj   the reference object with which to compare.
157      * @return  {@code true} if this object is the same as the obj
158      *          argument; {@code false} otherwise.
159      * @see     #hashCode()
160      * @see     java.util.HashMap
161      */
162     public boolean equals(Object obj) {
163         return (this == obj);
164     }
165 
166     /**
167      * Creates and returns a copy of this object.  The precise meaning
168      * of "copy" may depend on the class of the object. The general
169      * intent is that, for any object {@code x}, the expression:
170      * <blockquote>
171      * <pre>
172      * x.clone() != x</pre></blockquote>
173      * will be true, and that the expression:
174      * <blockquote>
175      * <pre>
176      * x.clone().getClass() == x.getClass()</pre></blockquote>
177      * will be {@code true}, but these are not absolute requirements.
178      * While it is typically the case that:
179      * <blockquote>
180      * <pre>
181      * x.clone().equals(x)</pre></blockquote>
182      * will be {@code true}, this is not an absolute requirement.
183      * <p>
184      * By convention, the returned object should be obtained by calling
185      * {@code super.clone}.  If a class and all of its superclasses (except
186      * {@code Object}) obey this convention, it will be the case that
187      * {@code x.clone().getClass() == x.getClass()}.
188      * <p>
189      * By convention, the object returned by this method should be independent
190      * of this object (which is being cloned).  To achieve this independence,
191      * it may be necessary to modify one or more fields of the object returned
192      * by {@code super.clone} before returning it.  Typically, this means
193      * copying any mutable objects that comprise the internal "deep structure"
194      * of the object being cloned and replacing the references to these
195      * objects with references to the copies.  If a class contains only
196      * primitive fields or references to immutable objects, then it is usually
197      * the case that no fields in the object returned by {@code super.clone}
198      * need to be modified.
199      *
200      * @implSpec
201      * The method {@code clone} for class {@code Object} performs a
202      * specific cloning operation. First, if the class of this object does
203      * not implement the interface {@code Cloneable}, then a
204      * {@code CloneNotSupportedException} is thrown. Note that all arrays
205      * are considered to implement the interface {@code Cloneable} and that
206      * the return type of the {@code clone} method of an array type {@code T[]}
207      * is {@code T[]} where T is any reference or primitive type.
208      * Otherwise, this method creates a new instance of the class of this
209      * object and initializes all its fields with exactly the contents of
210      * the corresponding fields of this object, as if by assignment; the
211      * contents of the fields are not themselves cloned. Thus, this method
212      * performs a "shallow copy" of this object, not a "deep copy" operation.
213      * <p>
214      * The class {@code Object} does not itself implement the interface
215      * {@code Cloneable}, so calling the {@code clone} method on an object
216      * whose class is {@code Object} will result in throwing an
217      * exception at run time.
218      *
219      * @return     a clone of this instance.
220      * @throws  CloneNotSupportedException  if the object's class does not
221      *               support the {@code Cloneable} interface. Subclasses
222      *               that override the {@code clone} method can also
223      *               throw this exception to indicate that an instance cannot
224      *               be cloned.
225      * @see java.lang.Cloneable
226      */
227     @IntrinsicCandidate
228     protected native Object clone() throws CloneNotSupportedException;
229 
230     /**
231      * Returns a string representation of the object.
232      * @apiNote
233      * In general, the
234      * {@code toString} method returns a string that
235      * "textually represents" this object. The result should
236      * be a concise but informative representation that is easy for a
237      * person to read.
238      * It is recommended that all subclasses override this method.
239      * The string output is not necessarily stable over time or across
240      * JVM invocations.
241      * @implSpec
242      * The {@code toString} method for class {@code Object}
243      * returns a string consisting of the name of the class of which the
244      * object is an instance, the at-sign character `{@code @}', and
245      * the unsigned hexadecimal representation of the hash code of the
246      * object. In other words, this method returns a string equal to the
247      * value of:
248      * <blockquote>
249      * <pre>
250      * getClass().getName() + '@' + Integer.toHexString(hashCode())
251      * </pre></blockquote>
252      *
253      * @return  a string representation of the object.
254      */
255     public String toString() {
256         return getClass().getName() + "@" + Integer.toHexString(hashCode());
257     }
258 
259     /**
260      * Wakes up a single thread that is waiting on this object's
261      * monitor. If any threads are waiting on this object, one of them
262      * is chosen to be awakened. The choice is arbitrary and occurs at
263      * the discretion of the implementation. A thread waits on an object's
264      * monitor by calling one of the {@code wait} methods.
265      * <p>
266      * The awakened thread will not be able to proceed until the current
267      * thread relinquishes the lock on this object. The awakened thread will
268      * compete in the usual manner with any other threads that might be
269      * actively competing to synchronize on this object; for example, the
270      * awakened thread enjoys no reliable privilege or disadvantage in being
271      * the next thread to lock this object.
272      * <p>
273      * This method should only be called by a thread that is the owner
274      * of this object's monitor. A thread becomes the owner of the
275      * object's monitor in one of three ways:
276      * <ul>
277      * <li>By executing a synchronized instance method of that object.
278      * <li>By executing the body of a {@code synchronized} statement
279      *     that synchronizes on the object.
280      * <li>For objects of type {@code Class,} by executing a
281      *     static synchronized method of that class.
282      * </ul>
283      * <p>
284      * Only one thread at a time can own an object's monitor.
285      *
286      * @throws  IllegalMonitorStateException  if the current thread is not
287      *               the owner of this object's monitor.
288      * @see        java.lang.Object#notifyAll()
289      * @see        java.lang.Object#wait()
290      */
291     @IntrinsicCandidate
292     public final native void notify();
293 
294     /**
295      * Wakes up all threads that are waiting on this object's monitor. A
296      * thread waits on an object's monitor by calling one of the
297      * {@code wait} methods.
298      * <p>
299      * The awakened threads will not be able to proceed until the current
300      * thread relinquishes the lock on this object. The awakened threads
301      * will compete in the usual manner with any other threads that might
302      * be actively competing to synchronize on this object; for example,
303      * the awakened threads enjoy no reliable privilege or disadvantage in
304      * being the next thread to lock this object.
305      * <p>
306      * This method should only be called by a thread that is the owner
307      * of this object's monitor. See the {@code notify} method for a
308      * description of the ways in which a thread can become the owner of
309      * a monitor.
310      *
311      * @throws  IllegalMonitorStateException  if the current thread is not
312      *               the owner of this object's monitor.
313      * @see        java.lang.Object#notify()
314      * @see        java.lang.Object#wait()
315      */
316     @IntrinsicCandidate
317     public final native void notifyAll();
318 
319     /**
320      * Causes the current thread to wait until it is awakened, typically
321      * by being <em>notified</em> or <em>interrupted</em>.
322      * <p>
323      * In all respects, this method behaves as if {@code wait(0L, 0)}
324      * had been called. See the specification of the {@link #wait(long, int)} method
325      * for details.
326      *
327      * @throws IllegalMonitorStateException if the current thread is not
328      *         the owner of the object's monitor
329      * @throws InterruptedException if any thread interrupted the current thread before or
330      *         while the current thread was waiting. The <em>interrupted status</em> of the
331      *         current thread is cleared when this exception is thrown.
332      * @see    #notify()
333      * @see    #notifyAll()
334      * @see    #wait(long)
335      * @see    #wait(long, int)
336      */
337     public final void wait() throws InterruptedException {
338         wait(0L);
339     }
340 
341     /**
342      * Causes the current thread to wait until it is awakened, typically
343      * by being <em>notified</em> or <em>interrupted</em>, or until a
344      * certain amount of real time has elapsed.
345      * <p>
346      * In all respects, this method behaves as if {@code wait(timeoutMillis, 0)}
347      * had been called. See the specification of the {@link #wait(long, int)} method
348      * for details.
349      *
350      * @param  timeoutMillis the maximum time to wait, in milliseconds
351      * @throws IllegalArgumentException if {@code timeoutMillis} is negative
352      * @throws IllegalMonitorStateException if the current thread is not
353      *         the owner of the object's monitor
354      * @throws InterruptedException if any thread interrupted the current thread before or
355      *         while the current thread was waiting. The <em>interrupted status</em> of the
356      *         current thread is cleared when this exception is thrown.
357      * @see    #notify()
358      * @see    #notifyAll()
359      * @see    #wait()
360      * @see    #wait(long, int)
361      */
362     public final native void wait(long timeoutMillis) throws InterruptedException;
















363 
364     /**
365      * Causes the current thread to wait until it is awakened, typically
366      * by being <em>notified</em> or <em>interrupted</em>, or until a
367      * certain amount of real time has elapsed.
368      * <p>
369      * The current thread must own this object's monitor lock. See the
370      * {@link #notify notify} method for a description of the ways in which
371      * a thread can become the owner of a monitor lock.
372      * <p>
373      * This method causes the current thread (referred to here as <var>T</var>) to
374      * place itself in the wait set for this object and then to relinquish any
375      * and all synchronization claims on this object. Note that only the locks
376      * on this object are relinquished; any other objects on which the current
377      * thread may be synchronized remain locked while the thread waits.
378      * <p>
379      * Thread <var>T</var> then becomes disabled for thread scheduling purposes
380      * and lies dormant until one of the following occurs:
381      * <ul>
382      * <li>Some other thread invokes the {@code notify} method for this
383      * object and thread <var>T</var> happens to be arbitrarily chosen as
384      * the thread to be awakened.
385      * <li>Some other thread invokes the {@code notifyAll} method for this
386      * object.
387      * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
388      * thread <var>T</var>.
389      * <li>The specified amount of real time has elapsed, more or less.
390      * The amount of real time, in nanoseconds, is given by the expression
391      * {@code 1000000 * timeoutMillis + nanos}. If {@code timeoutMillis} and {@code nanos}
392      * are both zero, then real time is not taken into consideration and the
393      * thread waits until awakened by one of the other causes.
394      * <li>Thread <var>T</var> is awakened spuriously. (See below.)
395      * </ul>
396      * <p>
397      * The thread <var>T</var> is then removed from the wait set for this
398      * object and re-enabled for thread scheduling. It competes in the
399      * usual manner with other threads for the right to synchronize on the
400      * object; once it has regained control of the object, all its
401      * synchronization claims on the object are restored to the status quo
402      * ante - that is, to the situation as of the time that the {@code wait}
403      * method was invoked. Thread <var>T</var> then returns from the
404      * invocation of the {@code wait} method. Thus, on return from the
405      * {@code wait} method, the synchronization state of the object and of
406      * thread {@code T} is exactly as it was when the {@code wait} method
407      * was invoked.
408      * <p>
409      * A thread can wake up without being notified, interrupted, or timing out, a
410      * so-called <em>spurious wakeup</em>.  While this will rarely occur in practice,
411      * applications must guard against it by testing for the condition that should
412      * have caused the thread to be awakened, and continuing to wait if the condition
413      * is not satisfied. See the example below.
414      * <p>
415      * For more information on this topic, see section 14.2,
416      * "Condition Queues," in Brian Goetz and others' <em>Java Concurrency
417      * in Practice</em> (Addison-Wesley, 2006) or Item 69 in Joshua
418      * Bloch's <em>Effective Java, Second Edition</em> (Addison-Wesley,
419      * 2008).
420      * <p>
421      * If the current thread is {@linkplain java.lang.Thread#interrupt() interrupted}
422      * by any thread before or while it is waiting, then an {@code InterruptedException}
423      * is thrown.  The <em>interrupted status</em> of the current thread is cleared when
424      * this exception is thrown. This exception is not thrown until the lock status of
425      * this object has been restored as described above.
426      *
427      * @apiNote
428      * The recommended approach to waiting is to check the condition being awaited in
429      * a {@code while} loop around the call to {@code wait}, as shown in the example
430      * below. Among other things, this approach avoids problems that can be caused
431      * by spurious wakeups.
432      *
433      * <pre>{@code
434      *     synchronized (obj) {
435      *         while (<condition does not hold> and <timeout not exceeded>) {
436      *             long timeoutMillis = ... ; // recompute timeout values
437      *             int nanos = ... ;
438      *             obj.wait(timeoutMillis, nanos);
439      *         }
440      *         ... // Perform action appropriate to condition or timeout
441      *     }
442      * }</pre>
443      *
444      * @param  timeoutMillis the maximum time to wait, in milliseconds
445      * @param  nanos   additional time, in nanoseconds, in the range 0-999999 inclusive
446      * @throws IllegalArgumentException if {@code timeoutMillis} is negative,
447      *         or if the value of {@code nanos} is out of range
448      * @throws IllegalMonitorStateException if the current thread is not
449      *         the owner of the object's monitor
450      * @throws InterruptedException if any thread interrupted the current thread before or
451      *         while the current thread was waiting. The <em>interrupted status</em> of the
452      *         current thread is cleared when this exception is thrown.
453      * @see    #notify()
454      * @see    #notifyAll()
455      * @see    #wait()
456      * @see    #wait(long)
457      */
458     public final void wait(long timeoutMillis, int nanos) throws InterruptedException {
459         if (timeoutMillis < 0) {
460             throw new IllegalArgumentException("timeoutMillis value is negative");
461         }
462 
463         if (nanos < 0 || nanos > 999999) {
464             throw new IllegalArgumentException(
465                                 "nanosecond timeout value out of range");
466         }
467 
468         if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) {
469             timeoutMillis++;
470         }
471 
472         wait(timeoutMillis);
473     }
474 
475     /**
476      * Called by the garbage collector on an object when garbage collection
477      * determines that there are no more references to the object.
478      * A subclass overrides the {@code finalize} method to dispose of
479      * system resources or to perform other cleanup.
480      * <p>
481      * The general contract of {@code finalize} is that it is invoked
482      * if and when the Java virtual
483      * machine has determined that there is no longer any
484      * means by which this object can be accessed by any thread that has
485      * not yet died, except as a result of an action taken by the
486      * finalization of some other object or class which is ready to be
487      * finalized. The {@code finalize} method may take any action, including
488      * making this object available again to other threads; the usual purpose
489      * of {@code finalize}, however, is to perform cleanup actions before
490      * the object is irrevocably discarded. For example, the finalize method
491      * for an object that represents an input/output connection might perform
492      * explicit I/O transactions to break the connection before the object is
493      * permanently discarded.
494      * <p>
495      * The {@code finalize} method of class {@code Object} performs no
496      * special action; it simply returns normally. Subclasses of
497      * {@code Object} may override this definition.
498      * <p>
499      * The Java programming language does not guarantee which thread will
500      * invoke the {@code finalize} method for any given object. It is
501      * guaranteed, however, that the thread that invokes finalize will not
502      * be holding any user-visible synchronization locks when finalize is
503      * invoked. If an uncaught exception is thrown by the finalize method,
504      * the exception is ignored and finalization of that object terminates.
505      * <p>
506      * After the {@code finalize} method has been invoked for an object, no
507      * further action is taken until the Java virtual machine has again
508      * determined that there is no longer any means by which this object can
509      * be accessed by any thread that has not yet died, including possible
510      * actions by other objects or classes which are ready to be finalized,
511      * at which point the object may be discarded.
512      * <p>
513      * The {@code finalize} method is never invoked more than once by a Java
514      * virtual machine for any given object.
515      * <p>
516      * Any exception thrown by the {@code finalize} method causes
517      * the finalization of this object to be halted, but is otherwise
518      * ignored.
519      *
520      * @apiNote
521      * Classes that embed non-heap resources have many options
522      * for cleanup of those resources. The class must ensure that the
523      * lifetime of each instance is longer than that of any resource it embeds.
524      * {@link java.lang.ref.Reference#reachabilityFence} can be used to ensure that
525      * objects remain reachable while resources embedded in the object are in use.
526      * <p>
527      * A subclass should avoid overriding the {@code finalize} method
528      * unless the subclass embeds non-heap resources that must be cleaned up
529      * before the instance is collected.
530      * Finalizer invocations are not automatically chained, unlike constructors.
531      * If a subclass overrides {@code finalize} it must invoke the superclass
532      * finalizer explicitly.
533      * To guard against exceptions prematurely terminating the finalize chain,
534      * the subclass should use a {@code try-finally} block to ensure
535      * {@code super.finalize()} is always invoked. For example,
536      * <pre>{@code      @Override
537      *     protected void finalize() throws Throwable {
538      *         try {
539      *             ... // cleanup subclass state
540      *         } finally {
541      *             super.finalize();
542      *         }
543      *     }
544      * }</pre>
545      *
546      * @deprecated The finalization mechanism is inherently problematic.
547      * Finalization can lead to performance issues, deadlocks, and hangs.
548      * Errors in finalizers can lead to resource leaks; there is no way to cancel
549      * finalization if it is no longer necessary; and no ordering is specified
550      * among calls to {@code finalize} methods of different objects.
551      * Furthermore, there are no guarantees regarding the timing of finalization.
552      * The {@code finalize} method might be called on a finalizable object
553      * only after an indefinite delay, if at all.
554      *
555      * Classes whose instances hold non-heap resources should provide a method
556      * to enable explicit release of those resources, and they should also
557      * implement {@link AutoCloseable} if appropriate.
558      * The {@link java.lang.ref.Cleaner} and {@link java.lang.ref.PhantomReference}
559      * provide more flexible and efficient ways to release resources when an object
560      * becomes unreachable.
561      *
562      * @throws Throwable the {@code Exception} raised by this method
563      * @see java.lang.ref.WeakReference
564      * @see java.lang.ref.PhantomReference
565      * @jls 12.6 Finalization of Class Instances
566      */
567     @Deprecated(since="9")
568     protected void finalize() throws Throwable { }
569 }
--- EOF ---