1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.lang;
28 
29 /**
30  * Class {@code Object} is the root of the class hierarchy.
31  * Every class has {@code Object} as a superclass. All objects,
32  * including arrays, implement the methods of this class.
33  *
34  * @author  unascribed
35  * @see     java.lang.Class
36  * @since   JDK1.0
37  */
38 public class Object {
39 
40     private transient Class<?> shadow$_klass_;
41     private transient int shadow$_monitor_;
42 
43     /**
44      * Returns the runtime class of this {@code Object}. The returned
45      * {@code Class} object is the object that is locked by {@code
46      * static synchronized} methods of the represented class.
47      *
48      * <p><b>The actual result type is {@code Class<? extends |X|>}
49      * where {@code |X|} is the erasure of the static type of the
50      * expression on which {@code getClass} is called.</b> For
51      * example, no cast is required in this code fragment:</p>
52      *
53      * <p>
54      * {@code Number n = 0;                             }<br>
55      * {@code Class<? extends Number> c = n.getClass(); }
56      * </p>
57      *
58      * @return The {@code Class} object that represents the runtime
59      *         class of this object.
60      * @see    Class Literals, section 15.8.2 of
61      *         <cite>The Java&trade; Language Specification</cite>.
62      */
getClass()63     public final Class<?> getClass() {
64       return shadow$_klass_;
65     }
66 
67     /**
68      * Returns a hash code value for the object. This method is
69      * supported for the benefit of hash tables such as those provided by
70      * {@link java.util.HashMap}.
71      * <p>
72      * The general contract of {@code hashCode} is:
73      * <ul>
74      * <li>Whenever it is invoked on the same object more than once during
75      *     an execution of a Java application, the {@code hashCode} method
76      *     must consistently return the same integer, provided no information
77      *     used in {@code equals} comparisons on the object is modified.
78      *     This integer need not remain consistent from one execution of an
79      *     application to another execution of the same application.
80      * <li>If two objects are equal according to the {@code equals(Object)}
81      *     method, then calling the {@code hashCode} method on each of
82      *     the two objects must produce the same integer result.
83      * <li>It is <em>not</em> required that if two objects are unequal
84      *     according to the {@link java.lang.Object#equals(java.lang.Object)}
85      *     method, then calling the {@code hashCode} method on each of the
86      *     two objects must produce distinct integer results.  However, the
87      *     programmer should be aware that producing distinct integer results
88      *     for unequal objects may improve the performance of hash tables.
89      * </ul>
90      * <p>
91      * As much as is reasonably practical, the hashCode method defined by
92      * class {@code Object} does return distinct integers for distinct
93      * objects. (This is typically implemented by converting the internal
94      * address of the object into an integer, but this implementation
95      * technique is not required by the
96      * Java<font size="-2"><sup>TM</sup></font> programming language.)
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      */
hashCode()102     public int hashCode() {
103         int lockWord = shadow$_monitor_;
104         final int lockWordStateMask = 0xC0000000;  // Top 2 bits.
105         final int lockWordStateHash = 0x80000000;  // Top 2 bits are value 2 (kStateHash).
106         final int lockWordHashMask = 0x0FFFFFFF;  // Low 28 bits.
107         if ((lockWord & lockWordStateMask) == lockWordStateHash) {
108             return lockWord & lockWordHashMask;
109         }
110         return System.identityHashCode(this);
111     }
112 
113     /**
114      * Indicates whether some other object is "equal to" this one.
115      * <p>
116      * The {@code equals} method implements an equivalence relation
117      * on non-null object references:
118      * <ul>
119      * <li>It is <i>reflexive</i>: for any non-null reference value
120      *     {@code x}, {@code x.equals(x)} should return
121      *     {@code true}.
122      * <li>It is <i>symmetric</i>: for any non-null reference values
123      *     {@code x} and {@code y}, {@code x.equals(y)}
124      *     should return {@code true} if and only if
125      *     {@code y.equals(x)} returns {@code true}.
126      * <li>It is <i>transitive</i>: for any non-null reference values
127      *     {@code x}, {@code y}, and {@code z}, if
128      *     {@code x.equals(y)} returns {@code true} and
129      *     {@code y.equals(z)} returns {@code true}, then
130      *     {@code x.equals(z)} should return {@code true}.
131      * <li>It is <i>consistent</i>: for any non-null reference values
132      *     {@code x} and {@code y}, multiple invocations of
133      *     {@code x.equals(y)} consistently return {@code true}
134      *     or consistently return {@code false}, provided no
135      *     information used in {@code equals} comparisons on the
136      *     objects is modified.
137      * <li>For any non-null reference value {@code x},
138      *     {@code x.equals(null)} should return {@code false}.
139      * </ul>
140      * <p>
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      * <p>
148      * Note that it is generally necessary to override the {@code hashCode}
149      * method whenever this method is overridden, so as to maintain the
150      * general contract for the {@code hashCode} method, which states
151      * that equal objects must have equal hash codes.
152      *
153      * @param   obj   the reference object with which to compare.
154      * @return  {@code true} if this object is the same as the obj
155      *          argument; {@code false} otherwise.
156      * @see     #hashCode()
157      * @see     java.util.HashMap
158      */
equals(Object obj)159     public boolean equals(Object obj) {
160         return (this == obj);
161     }
162 
163     /**
164      * Creates and returns a copy of this object.  The precise meaning
165      * of "copy" may depend on the class of the object. The general
166      * intent is that, for any object {@code x}, the expression:
167      * <blockquote>
168      * <pre>
169      * x.clone() != x</pre></blockquote>
170      * will be true, and that the expression:
171      * <blockquote>
172      * <pre>
173      * x.clone().getClass() == x.getClass()</pre></blockquote>
174      * will be {@code true}, but these are not absolute requirements.
175      * While it is typically the case that:
176      * <blockquote>
177      * <pre>
178      * x.clone().equals(x)</pre></blockquote>
179      * will be {@code true}, this is not an absolute requirement.
180      * <p>
181      * By convention, the returned object should be obtained by calling
182      * {@code super.clone}.  If a class and all of its superclasses (except
183      * {@code Object}) obey this convention, it will be the case that
184      * {@code x.clone().getClass() == x.getClass()}.
185      * <p>
186      * By convention, the object returned by this method should be independent
187      * of this object (which is being cloned).  To achieve this independence,
188      * it may be necessary to modify one or more fields of the object returned
189      * by {@code super.clone} before returning it.  Typically, this means
190      * copying any mutable objects that comprise the internal "deep structure"
191      * of the object being cloned and replacing the references to these
192      * objects with references to the copies.  If a class contains only
193      * primitive fields or references to immutable objects, then it is usually
194      * the case that no fields in the object returned by {@code super.clone}
195      * need to be modified.
196      * <p>
197      * The method {@code clone} for class {@code Object} performs a
198      * specific cloning operation. First, if the class of this object does
199      * not implement the interface {@code Cloneable}, then a
200      * {@code CloneNotSupportedException} is thrown. Note that all arrays
201      * are considered to implement the interface {@code Cloneable} and that
202      * the return type of the {@code clone} method of an array type {@code T[]}
203      * is {@code T[]} where T is any reference or primitive type.
204      * Otherwise, this method creates a new instance of the class of this
205      * object and initializes all its fields with exactly the contents of
206      * the corresponding fields of this object, as if by assignment; the
207      * contents of the fields are not themselves cloned. Thus, this method
208      * performs a "shallow copy" of this object, not a "deep copy" operation.
209      * <p>
210      * The class {@code Object} does not itself implement the interface
211      * {@code Cloneable}, so calling the {@code clone} method on an object
212      * whose class is {@code Object} will result in throwing an
213      * exception at run time.
214      *
215      * @return     a clone of this instance.
216      * @exception  CloneNotSupportedException  if the object's class does not
217      *               support the {@code Cloneable} interface. Subclasses
218      *               that override the {@code clone} method can also
219      *               throw this exception to indicate that an instance cannot
220      *               be cloned.
221      * @see java.lang.Cloneable
222      */
clone()223     protected Object clone() throws CloneNotSupportedException {
224         if (!(this instanceof Cloneable)) {
225             throw new CloneNotSupportedException("Class " + getClass().getName() +
226                                                  " doesn't implement Cloneable");
227         }
228 
229         return internalClone();
230     }
231 
232     /*
233      * Native helper method for cloning.
234      */
internalClone()235     private native Object internalClone();
236 
237 
238     /**
239      * Returns a string representation of the object. In general, the
240      * {@code toString} method returns a string that
241      * "textually represents" this object. The result should
242      * be a concise but informative representation that is easy for a
243      * person to read.
244      * It is recommended that all subclasses override this method.
245      * <p>
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      *
257      * @return  a string representation of the object.
258      */
toString()259     public String toString() {
260         return getClass().getName() + "@" + Integer.toHexString(hashCode());
261     }
262 
263     /**
264      * Wakes up a single thread that is waiting on this object's
265      * monitor. If any threads are waiting on this object, one of them
266      * is chosen to be awakened. The choice is arbitrary and occurs at
267      * the discretion of the implementation. A thread waits on an object's
268      * monitor by calling one of the {@code wait} methods.
269      * <p>
270      * The awakened thread will not be able to proceed until the current
271      * thread relinquishes the lock on this object. The awakened thread will
272      * compete in the usual manner with any other threads that might be
273      * actively competing to synchronize on this object; for example, the
274      * awakened thread enjoys no reliable privilege or disadvantage in being
275      * the next thread to lock this object.
276      * <p>
277      * This method should only be called by a thread that is the owner
278      * of this object's monitor. A thread becomes the owner of the
279      * object's monitor in one of three ways:
280      * <ul>
281      * <li>By executing a synchronized instance method of that object.
282      * <li>By executing the body of a {@code synchronized} statement
283      *     that synchronizes on the object.
284      * <li>For objects of type {@code Class,} by executing a
285      *     synchronized static method of that class.
286      * </ul>
287      * <p>
288      * Only one thread at a time can own an object's monitor.
289      *
290      * @exception  IllegalMonitorStateException  if the current thread is not
291      *               the owner of this object's monitor.
292      * @see        java.lang.Object#notifyAll()
293      * @see        java.lang.Object#wait()
294      */
notify()295     public final native void notify();
296 
297     /**
298      * Wakes up all threads that are waiting on this object's monitor. A
299      * thread waits on an object's monitor by calling one of the
300      * {@code wait} methods.
301      * <p>
302      * The awakened threads will not be able to proceed until the current
303      * thread relinquishes the lock on this object. The awakened threads
304      * will compete in the usual manner with any other threads that might
305      * be actively competing to synchronize on this object; for example,
306      * the awakened threads enjoy no reliable privilege or disadvantage in
307      * being the next thread to lock this object.
308      * <p>
309      * This method should only be called by a thread that is the owner
310      * of this object's monitor. See the {@code notify} method for a
311      * description of the ways in which a thread can become the owner of
312      * a monitor.
313      *
314      * @exception  IllegalMonitorStateException  if the current thread is not
315      *               the owner of this object's monitor.
316      * @see        java.lang.Object#notify()
317      * @see        java.lang.Object#wait()
318      */
notifyAll()319     public final native void notifyAll();
320 
321     /**
322      * Causes the current thread to wait until either another thread invokes the
323      * {@link java.lang.Object#notify()} method or the
324      * {@link java.lang.Object#notifyAll()} method for this object, or a
325      * specified amount of time has elapsed.
326      * <p>
327      * The current thread must own this object's monitor.
328      * <p>
329      * This method causes the current thread (call it <var>T</var>) to
330      * place itself in the wait set for this object and then to relinquish
331      * any and all synchronization claims on this object. Thread <var>T</var>
332      * becomes disabled for thread scheduling purposes and lies dormant
333      * until one of four things happens:
334      * <ul>
335      * <li>Some other thread invokes the {@code notify} method for this
336      * object and thread <var>T</var> happens to be arbitrarily chosen as
337      * the thread to be awakened.
338      * <li>Some other thread invokes the {@code notifyAll} method for this
339      * object.
340      * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
341      * thread <var>T</var>.
342      * <li>The specified amount of real time has elapsed, more or less.  If
343      * {@code timeout} is zero, however, then real time is not taken into
344      * consideration and the thread simply waits until notified.
345      * </ul>
346      * The thread <var>T</var> is then removed from the wait set for this
347      * object and re-enabled for thread scheduling. It then competes in the
348      * usual manner with other threads for the right to synchronize on the
349      * object; once it has gained control of the object, all its
350      * synchronization claims on the object are restored to the status quo
351      * ante - that is, to the situation as of the time that the {@code wait}
352      * method was invoked. Thread <var>T</var> then returns from the
353      * invocation of the {@code wait} method. Thus, on return from the
354      * {@code wait} method, the synchronization state of the object and of
355      * thread {@code T} is exactly as it was when the {@code wait} method
356      * was invoked.
357      * <p>
358      * A thread can also wake up without being notified, interrupted, or
359      * timing out, a so-called <i>spurious wakeup</i>.  While this will rarely
360      * occur in practice, applications must guard against it by testing for
361      * the condition that should have caused the thread to be awakened, and
362      * continuing to wait if the condition is not satisfied.  In other words,
363      * waits should always occur in loops, like this one:
364      * <pre>
365      *     synchronized (obj) {
366      *         while (&lt;condition does not hold&gt;)
367      *             obj.wait(timeout);
368      *         ... // Perform action appropriate to condition
369      *     }
370      * </pre>
371      * (For more information on this topic, see Section 3.2.3 in Doug Lea's
372      * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
373      * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
374      * Language Guide" (Addison-Wesley, 2001).
375      *
376      * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
377      * interrupted} by any thread before or while it is waiting, then an
378      * {@code InterruptedException} is thrown.  This exception is not
379      * thrown until the lock status of this object has been restored as
380      * described above.
381      *
382      * <p>
383      * Note that the {@code wait} method, as it places the current thread
384      * into the wait set for this object, unlocks only this object; any
385      * other objects on which the current thread may be synchronized remain
386      * locked while the thread waits.
387      * <p>
388      * This method should only be called by a thread that is the owner
389      * of this object's monitor. See the {@code notify} method for a
390      * description of the ways in which a thread can become the owner of
391      * a monitor.
392      *
393      * @param      millis   the maximum time to wait in milliseconds.
394      * @exception  IllegalArgumentException      if the value of timeout is
395      *               negative.
396      * @exception  IllegalMonitorStateException  if the current thread is not
397      *               the owner of the object's monitor.
398      * @exception  InterruptedException if any thread interrupted the
399      *             current thread before or while the current thread
400      *             was waiting for a notification.  The <i>interrupted
401      *             status</i> of the current thread is cleared when
402      *             this exception is thrown.
403      * @see        java.lang.Object#notify()
404      * @see        java.lang.Object#notifyAll()
405      */
wait(long millis)406     public final void wait(long millis) throws InterruptedException {
407         wait(millis, 0);
408     }
409 
410     /**
411      * Causes the current thread to wait until another thread invokes the
412      * {@link java.lang.Object#notify()} method or the
413      * {@link java.lang.Object#notifyAll()} method for this object, or
414      * some other thread interrupts the current thread, or a certain
415      * amount of real time has elapsed.
416      * <p>
417      * This method is similar to the {@code wait} method of one
418      * argument, but it allows finer control over the amount of time to
419      * wait for a notification before giving up. The amount of real time,
420      * measured in nanoseconds, is given by:
421      * <blockquote>
422      * <pre>
423      * 1000000*timeout+nanos</pre></blockquote>
424      * <p>
425      * In all other respects, this method does the same thing as the
426      * method {@link #wait(long)} of one argument. In particular,
427      * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
428      * <p>
429      * The current thread must own this object's monitor. The thread
430      * releases ownership of this monitor and waits until either of the
431      * following two conditions has occurred:
432      * <ul>
433      * <li>Another thread notifies threads waiting on this object's monitor
434      *     to wake up either through a call to the {@code notify} method
435      *     or the {@code notifyAll} method.
436      * <li>The timeout period, specified by {@code timeout}
437      *     milliseconds plus {@code nanos} nanoseconds arguments, has
438      *     elapsed.
439      * </ul>
440      * <p>
441      * The thread then waits until it can re-obtain ownership of the
442      * monitor and resumes execution.
443      * <p>
444      * As in the one argument version, interrupts and spurious wakeups are
445      * possible, and this method should always be used in a loop:
446      * <pre>
447      *     synchronized (obj) {
448      *         while (&lt;condition does not hold&gt;)
449      *             obj.wait(timeout, nanos);
450      *         ... // Perform action appropriate to condition
451      *     }
452      * </pre>
453      * This method should only be called by a thread that is the owner
454      * of this object's monitor. See the {@code notify} method for a
455      * description of the ways in which a thread can become the owner of
456      * a monitor.
457      *
458      * @param      millis   the maximum time to wait in milliseconds.
459      * @param      nanos      additional time, in nanoseconds range
460      *                       0-999999.
461      * @exception  IllegalArgumentException      if the value of timeout is
462      *                      negative or the value of nanos is
463      *                      not in the range 0-999999.
464      * @exception  IllegalMonitorStateException  if the current thread is not
465      *               the owner of this object's monitor.
466      * @exception  InterruptedException if any thread interrupted the
467      *             current thread before or while the current thread
468      *             was waiting for a notification.  The <i>interrupted
469      *             status</i> of the current thread is cleared when
470      *             this exception is thrown.
471      */
wait(long millis, int nanos)472     public final native void wait(long millis, int nanos) throws InterruptedException;
473 
474     /**
475      * Causes the current thread to wait until another thread invokes the
476      * {@link java.lang.Object#notify()} method or the
477      * {@link java.lang.Object#notifyAll()} method for this object.
478      * In other words, this method behaves exactly as if it simply
479      * performs the call {@code wait(0)}.
480      * <p>
481      * The current thread must own this object's monitor. The thread
482      * releases ownership of this monitor and waits until another thread
483      * notifies threads waiting on this object's monitor to wake up
484      * either through a call to the {@code notify} method or the
485      * {@code notifyAll} method. The thread then waits until it can
486      * re-obtain ownership of the monitor and resumes execution.
487      * <p>
488      * As in the one argument version, interrupts and spurious wakeups are
489      * possible, and this method should always be used in a loop:
490      * <pre>
491      *     synchronized (obj) {
492      *         while (&lt;condition does not hold&gt;)
493      *             obj.wait();
494      *         ... // Perform action appropriate to condition
495      *     }
496      * </pre>
497      * This method should only be called by a thread that is the owner
498      * of this object's monitor. See the {@code notify} method for a
499      * description of the ways in which a thread can become the owner of
500      * a monitor.
501      *
502      * @exception  IllegalMonitorStateException  if the current thread is not
503      *               the owner of the object's monitor.
504      * @exception  InterruptedException if any thread interrupted the
505      *             current thread before or while the current thread
506      *             was waiting for a notification.  The <i>interrupted
507      *             status</i> of the current thread is cleared when
508      *             this exception is thrown.
509      * @see        java.lang.Object#notify()
510      * @see        java.lang.Object#notifyAll()
511      */
wait()512     public final native void wait() throws InterruptedException;
513 
514     /**
515      * Called by the garbage collector on an object when garbage collection
516      * determines that there are no more references to the object.
517      * A subclass overrides the {@code finalize} method to dispose of
518      * system resources or to perform other cleanup.
519      * <p>
520      * The general contract of {@code finalize} is that it is invoked
521      * if and when the Java<font size="-2"><sup>TM</sup></font> virtual
522      * machine has determined that there is no longer any
523      * means by which this object can be accessed by any thread that has
524      * not yet died, except as a result of an action taken by the
525      * finalization of some other object or class which is ready to be
526      * finalized. The {@code finalize} method may take any action, including
527      * making this object available again to other threads; the usual purpose
528      * of {@code finalize}, however, is to perform cleanup actions before
529      * the object is irrevocably discarded. For example, the finalize method
530      * for an object that represents an input/output connection might perform
531      * explicit I/O transactions to break the connection before the object is
532      * permanently discarded.
533      * <p>
534      * The {@code finalize} method of class {@code Object} performs no
535      * special action; it simply returns normally. Subclasses of
536      * {@code Object} may override this definition.
537      * <p>
538      * The Java programming language does not guarantee which thread will
539      * invoke the {@code finalize} method for any given object. It is
540      * guaranteed, however, that the thread that invokes finalize will not
541      * be holding any user-visible synchronization locks when finalize is
542      * invoked. If an uncaught exception is thrown by the finalize method,
543      * the exception is ignored and finalization of that object terminates.
544      * <p>
545      * After the {@code finalize} method has been invoked for an object, no
546      * further action is taken until the Java virtual machine has again
547      * determined that there is no longer any means by which this object can
548      * be accessed by any thread that has not yet died, including possible
549      * actions by other objects or classes which are ready to be finalized,
550      * at which point the object may be discarded.
551      * <p>
552      * The {@code finalize} method is never invoked more than once by a Java
553      * virtual machine for any given object.
554      * <p>
555      * Any exception thrown by the {@code finalize} method causes
556      * the finalization of this object to be halted, but is otherwise
557      * ignored.
558      *
559      * @throws Throwable the {@code Exception} raised by this method
560      */
finalize()561     protected void finalize() throws Throwable { }
562 }
563