• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 /*
18  * Copyright (C) 2008 The Android Open Source Project
19  *
20  * Licensed under the Apache License, Version 2.0 (the "License");
21  * you may not use this file except in compliance with the License.
22  * You may obtain a copy of the License at
23  *
24  *      http://www.apache.org/licenses/LICENSE-2.0
25  *
26  * Unless required by applicable law or agreed to in writing, software
27  * distributed under the License is distributed on an "AS IS" BASIS,
28  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29  * See the License for the specific language governing permissions and
30  * limitations under the License.
31  */
32 
33 package java.lang;
34 
35 /**
36  * The root class of the Java class hierarchy. All non-primitive types
37  * (including arrays) inherit either directly or indirectly from this class.
38  *
39  * <a name="writing_equals"><h4>Writing a correct {@code equals} method</h4></a>
40  * <p>Follow this style to write a canonical {@code equals} method:
41  * <pre>
42  *   // Use @Override to avoid accidental overloading.
43  *   &#x0040;Override public boolean equals(Object o) {
44  *     // Return true if the objects are identical.
45  *     // (This is just an optimization, not required for correctness.)
46  *     if (this == o) {
47  *       return true;
48  *     }
49  *
50  *     // Return false if the other object has the wrong type.
51  *     // This type may be an interface depending on the interface's specification.
52  *     if (!(o instanceof MyType)) {
53  *       return false;
54  *     }
55  *
56  *     // Cast to the appropriate type.
57  *     // This will succeed because of the instanceof, and lets us access private fields.
58  *     MyType lhs = (MyType) o;
59  *
60  *     // Check each field. Primitive fields, reference fields, and nullable reference
61  *     // fields are all treated differently.
62  *     return primitiveField == lhs.primitiveField &amp;&amp;
63  *             referenceField.equals(lhs.referenceField) &amp;&amp;
64  *             (nullableField == null ? lhs.nullableField == null
65  *                                    : nullableField.equals(lhs.nullableField));
66  *   }
67  * </pre>
68  * <p>If you override {@code equals}, you should also override {@code hashCode}: equal
69  * instances must have equal hash codes.
70  *
71  * <p>See <i>Effective Java</i> item 8 for much more detail and clarification.
72  *
73  * <a name="writing_hashCode"><h4>Writing a correct {@code hashCode} method</h4></a>
74  * <p>Follow this style to write a canonical {@code hashCode} method:
75  * <pre>
76  *   &#x0040;Override public int hashCode() {
77  *     // Start with a non-zero constant.
78  *     int result = 17;
79  *
80  *     // Include a hash for each field.
81  *     result = 31 * result + (booleanField ? 1 : 0);
82  *
83  *     result = 31 * result + byteField;
84  *     result = 31 * result + charField;
85  *     result = 31 * result + shortField;
86  *     result = 31 * result + intField;
87  *
88  *     result = 31 * result + (int) (longField ^ (longField >>> 32));
89  *
90  *     result = 31 * result + Float.floatToIntBits(floatField);
91  *
92  *     long doubleFieldBits = Double.doubleToLongBits(doubleField);
93  *     result = 31 * result + (int) (doubleFieldBits ^ (doubleFieldBits >>> 32));
94  *
95  *     result = 31 * result + Arrays.hashCode(arrayField);
96  *
97  *     result = 31 * result + referenceField.hashCode();
98  *     result = 31 * result +
99  *         (nullableReferenceField == null ? 0
100  *                                         : nullableReferenceField.hashCode());
101  *
102  *     return result;
103  *   }
104  * </pre>
105  *
106  * <p>If you don't intend your type to be used as a hash key, don't simply rely on the default
107  * {@code hashCode} implementation, because that silently and non-obviously breaks any future
108  * code that does use your type as a hash key. You should throw instead:
109  * <pre>
110  *   &#x0040;Override public int hashCode() {
111  *     throw new UnsupportedOperationException();
112  *   }
113  * </pre>
114  *
115  * <p>See <i>Effective Java</i> item 9 for much more detail and clarification.
116  *
117  * <a name="writing_toString"><h4>Writing a useful {@code toString} method</h4></a>
118  * <p>For debugging convenience, it's common to override {@code toString} in this style:
119  * <pre>
120  *   &#x0040;Override public String toString() {
121  *     return getClass().getName() + "[" +
122  *         "primitiveField=" + primitiveField + ", " +
123  *         "referenceField=" + referenceField + ", " +
124  *         "arrayField=" + Arrays.toString(arrayField) + "]";
125  *   }
126  * </pre>
127  * <p>The set of fields to include is generally the same as those that would be tested
128  * in your {@code equals} implementation.
129  * <p>See <i>Effective Java</i> item 10 for much more detail and clarification.
130  */
131 public class Object {
132 
133     private transient Class<?> shadow$_klass_;
134     private transient int shadow$_monitor_;
135 
136     // Uncomment the following two fields to enable brooks pointers.
137     // Meant to do "#ifdef USE_BROOKS_POINTER ... #endif" but no macros.
138     //
139     // Note names use a 'x' prefix and the _x_rb_ptr_ field is of
140     // type int instead of Object to go with the alphabetical/by-type
141     // field order.
142     // private transient int shadow$_x_rb_ptr_;
143     // private transient int shadow$_x_xpadding_;
144 
145     /**
146      * Constructs a new instance of {@code Object}.
147      */
Object()148     public Object() {
149     }
150 
151     /**
152      * Creates and returns a copy of this {@code Object}. The default
153      * implementation returns a so-called "shallow" copy: It creates a new
154      * instance of the same class and then copies the field values (including
155      * object references) from this instance to the new instance. A "deep" copy,
156      * in contrast, would also recursively clone nested objects. A subclass that
157      * needs to implement this kind of cloning should call {@code super.clone()}
158      * to create the new instance and then create deep copies of the nested,
159      * mutable objects.
160      *
161      * @return a copy of this object.
162      * @throws CloneNotSupportedException
163      *             if this object's class does not implement the {@code
164      *             Cloneable} interface.
165      */
clone()166     protected Object clone() throws CloneNotSupportedException {
167         if (!(this instanceof Cloneable)) {
168             throw new CloneNotSupportedException("Class " + getClass().getName() +
169                                                  " doesn't implement Cloneable");
170         }
171 
172         return internalClone();
173     }
174 
175     /*
176      * Native helper method for cloning.
177      */
internalClone()178     private native Object internalClone();
179 
180     /**
181      * Compares this instance with the specified object and indicates if they
182      * are equal. In order to be equal, {@code o} must represent the same object
183      * as this instance using a class-specific comparison. The general contract
184      * is that this comparison should be reflexive, symmetric, and transitive.
185      * Also, no object reference other than null is equal to null.
186      *
187      * <p>The default implementation returns {@code true} only if {@code this ==
188      * o}. See <a href="{@docRoot}reference/java/lang/Object.html#writing_equals">Writing a correct
189      * {@code equals} method</a>
190      * if you intend implementing your own {@code equals} method.
191      *
192      * <p>The general contract for the {@code equals} and {@link
193      * #hashCode()} methods is that if {@code equals} returns {@code true} for
194      * any two objects, then {@code hashCode()} must return the same value for
195      * these objects. This means that subclasses of {@code Object} usually
196      * override either both methods or neither of them.
197      *
198      * @param o
199      *            the object to compare this instance with.
200      * @return {@code true} if the specified object is equal to this {@code
201      *         Object}; {@code false} otherwise.
202      * @see #hashCode
203      */
equals(Object o)204     public boolean equals(Object o) {
205         return this == o;
206     }
207 
208     /**
209      * Invoked when the garbage collector has detected that this instance is no longer reachable.
210      * The default implementation does nothing, but this method can be overridden to free resources.
211      *
212      * <p>Note that objects that override {@code finalize} are significantly more expensive than
213      * objects that don't. Finalizers may be run a long time after the object is no longer
214      * reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
215      * Note also that finalizers are run on a single VM-wide finalizer thread,
216      * so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
217      * for a class that has a native peer and needs to call a native method to destroy that peer.
218      * Even then, it's better to provide an explicit {@code close} method (and implement
219      * {@link java.io.Closeable}), and insist that callers manually dispose of instances. This
220      * works well for something like files, but less well for something like a {@code BigInteger}
221      * where typical calling code would have to deal with lots of temporaries. Unfortunately,
222      * code that creates lots of temporaries is the worst kind of code from the point of view of
223      * the single finalizer thread.
224      *
225      * <p>If you <i>must</i> use finalizers, consider at least providing your own
226      * {@link java.lang.ref.ReferenceQueue} and having your own thread process that queue.
227      *
228      * <p>Unlike constructors, finalizers are not automatically chained. You are responsible for
229      * calling {@code super.finalize()} yourself.
230      *
231      * <p>Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer
232      * thread.
233      *
234      * See <i>Effective Java</i> Item 7, "Avoid finalizers" for more.
235      */
236     @FindBugsSuppressWarnings("FI_EMPTY")
finalize()237     protected void finalize() throws Throwable {
238     }
239 
240     /**
241      * Returns the unique instance of {@link Class} that represents this
242      * object's class. Note that {@code getClass()} is a special case in that it
243      * actually returns {@code Class<? extends Foo>} where {@code Foo} is the
244      * erasure of the type of the expression {@code getClass()} was called upon.
245      * <p>
246      * As an example, the following code actually compiles, although one might
247      * think it shouldn't:
248      * <p>
249      * <pre>{@code
250      *   List<Integer> l = new ArrayList<Integer>();
251      *   Class<? extends List> c = l.getClass();}</pre>
252      *
253      * @return this object's {@code Class} instance.
254      */
getClass()255     public final Class<?> getClass() {
256       return shadow$_klass_;
257     }
258 
259     /**
260      * Returns an integer hash code for this object. By contract, any two
261      * objects for which {@link #equals} returns {@code true} must return
262      * the same hash code value. This means that subclasses of {@code Object}
263      * usually override both methods or neither method.
264      *
265      * <p>Note that hash values must not change over time unless information used in equals
266      * comparisons also changes.
267      *
268      * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_hashCode">Writing a correct
269      * {@code hashCode} method</a>
270      * if you intend implementing your own {@code hashCode} method.
271      *
272      * @return this object's hash code.
273      * @see #equals
274      */
hashCode()275     public int hashCode() {
276         int lockWord = shadow$_monitor_;
277         final int lockWordStateMask = 0xC0000000;  // Top 2 bits.
278         final int lockWordStateHash = 0x80000000;  // Top 2 bits are value 2 (kStateHash).
279         final int lockWordHashMask = 0x0FFFFFFF;  // Low 28 bits.
280         if ((lockWord & lockWordStateMask) == lockWordStateHash) {
281             return lockWord & lockWordHashMask;
282         }
283         return System.identityHashCode(this);
284     }
285 
286     /**
287      * Causes a thread which is waiting on this object's monitor (by means of
288      * calling one of the {@code wait()} methods) to be woken up. If more than
289      * one thread is waiting, one of them is chosen at the discretion of the
290      * VM. The chosen thread will not run immediately. The thread
291      * that called {@code notify()} has to release the object's monitor first.
292      * Also, the chosen thread still has to compete against other threads that
293      * try to synchronize on the same object.
294      *
295      * <p>This method can only be invoked by a thread which owns this object's
296      * monitor. A thread becomes owner of an object's monitor
297      * <ul>
298      * <li>by executing a synchronized method of that object;</li>
299      * <li>by executing the body of a {@code synchronized} statement that
300      * synchronizes on the object;</li>
301      * <li>by executing a synchronized static method if the object is of type
302      * {@code Class}.</li>
303      * </ul>
304      *
305      * @see #notifyAll
306      * @see #wait()
307      * @see #wait(long)
308      * @see #wait(long,int)
309      * @see java.lang.Thread
310      */
notify()311     public final native void notify();
312 
313     /**
314      * Causes all threads which are waiting on this object's monitor (by means
315      * of calling one of the {@code wait()} methods) to be woken up. The threads
316      * will not run immediately. The thread that called {@code notify()} has to
317      * release the object's monitor first. Also, the threads still have to
318      * compete against other threads that try to synchronize on the same object.
319      *
320      * <p>This method can only be invoked by a thread which owns this object's
321      * monitor. A thread becomes owner of an object's monitor
322      * <ul>
323      * <li>by executing a synchronized method of that object;</li>
324      * <li>by executing the body of a {@code synchronized} statement that
325      * synchronizes on the object;</li>
326      * <li>by executing a synchronized static method if the object is of type
327      * {@code Class}.</li>
328      * </ul>
329      *
330      * @throws IllegalMonitorStateException
331      *             if the thread calling this method is not the owner of this
332      *             object's monitor.
333      * @see #notify
334      * @see #wait()
335      * @see #wait(long)
336      * @see #wait(long,int)
337      * @see java.lang.Thread
338      */
notifyAll()339     public final native void notifyAll();
340 
341     /**
342      * Returns a string containing a concise, human-readable description of this
343      * object. Subclasses are encouraged to override this method and provide an
344      * implementation that takes into account the object's type and data. The
345      * default implementation is equivalent to the following expression:
346      * <pre>
347      *   getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>
348      * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_toString">Writing a useful
349      * {@code toString} method</a>
350      * if you intend implementing your own {@code toString} method.
351      *
352      * @return a printable representation of this object.
353      */
toString()354     public String toString() {
355         return getClass().getName() + '@' + Integer.toHexString(hashCode());
356     }
357 
358     /**
359      * Causes the calling thread to wait until another thread calls the {@code
360      * notify()} or {@code notifyAll()} method of this object. This method can
361      * only be invoked by a thread which owns this object's monitor; see
362      * {@link #notify()} on how a thread can become the owner of a monitor.
363      *
364      * <p>A waiting thread can be sent {@code interrupt()} to cause it to
365      * prematurely stop waiting, so {@code wait} should be called in a loop to
366      * check that the condition that has been waited for has been met before
367      * continuing.
368      *
369      * <p>While the thread waits, it gives up ownership of this object's
370      * monitor. When it is notified (or interrupted), it re-acquires the monitor
371      * before it starts running.
372      *
373      * @throws IllegalMonitorStateException
374      *             if the thread calling this method is not the owner of this
375      *             object's monitor.
376      * @throws InterruptedException if the current thread has been interrupted.
377      *             The interrupted status of the current thread will be cleared before the exception
378      *             is thrown.
379      * @see #notify
380      * @see #notifyAll
381      * @see #wait(long)
382      * @see #wait(long,int)
383      * @see java.lang.Thread
384      */
wait()385     public final native void wait() throws InterruptedException;
386 
387     /**
388      * Causes the calling thread to wait until another thread calls the {@code
389      * notify()} or {@code notifyAll()} method of this object or until the
390      * specified timeout expires. This method can only be invoked by a thread
391      * which owns this object's monitor; see {@link #notify()} on how a thread
392      * can become the owner of a monitor.
393      *
394      * <p>A waiting thread can be sent {@code interrupt()} to cause it to
395      * prematurely stop waiting, so {@code wait} should be called in a loop to
396      * check that the condition that has been waited for has been met before
397      * continuing.
398      *
399      * <p>While the thread waits, it gives up ownership of this object's
400      * monitor. When it is notified (or interrupted), it re-acquires the monitor
401      * before it starts running.
402      *
403      * <p>A timeout of zero means the calling thread should wait forever unless interrupted or
404      * notified.
405      *
406      * @param millis
407      *            the maximum time to wait in milliseconds.
408      * @throws IllegalArgumentException
409      *             if {@code millis < 0}.
410      * @throws IllegalMonitorStateException
411      *             if the thread calling this method is not the owner of this
412      *             object's monitor.
413      * @throws InterruptedException if the current thread has been interrupted.
414      *             The interrupted status of the current thread will be cleared before the exception
415      *             is thrown.
416      * @see #notify
417      * @see #notifyAll
418      * @see #wait()
419      * @see #wait(long,int)
420      * @see java.lang.Thread
421      */
wait(long millis)422     public final void wait(long millis) throws InterruptedException {
423         wait(millis, 0);
424     }
425 
426     /**
427      * Causes the calling thread to wait until another thread calls the {@code
428      * notify()} or {@code notifyAll()} method of this object or until the
429      * specified timeout expires. This method can only be invoked by a thread
430      * that owns this object's monitor; see {@link #notify()} on how a thread
431      * can become the owner of a monitor.
432      *
433      * <p>A waiting thread can be sent {@code interrupt()} to cause it to
434      * prematurely stop waiting, so {@code wait} should be called in a loop to
435      * check that the condition that has been waited for has been met before
436      * continuing.
437      *
438      * <p>While the thread waits, it gives up ownership of this object's
439      * monitor. When it is notified (or interrupted), it re-acquires the monitor
440      * before it starts running.
441      *
442      * <p>A timeout of zero means the calling thread should wait forever unless interrupted or
443      * notified.
444      *
445      * @param millis
446      *            the maximum time to wait in milliseconds.
447      * @param nanos
448      *            the fraction of a millisecond to wait, specified in
449      *            nanoseconds.
450      * @throws IllegalArgumentException
451      *             if {@code millis < 0}, {@code nanos < 0} or {@code nanos >
452      *             999999}.
453      * @throws IllegalMonitorStateException
454      *             if the thread calling this method is not the owner of this
455      *             object's monitor.
456      * @throws InterruptedException if the current thread has been interrupted.
457      *             The interrupted status of the current thread will be cleared before the exception
458      *             is thrown.
459      * @see #notify
460      * @see #notifyAll
461      * @see #wait()
462      * @see #wait(long,int)
463      * @see java.lang.Thread
464      */
wait(long millis, int nanos)465     public final native void wait(long millis, int nanos) throws InterruptedException;
466 }
467