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