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