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
33package 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 */
131public class Object {
132
133    private transient Class<?> shadow$_klass_;
134    private transient int shadow$_monitor_;
135
136    /**
137     * Constructs a new instance of {@code Object}.
138     */
139    public Object() {
140      if (shadow$_klass_.isFinalizable()) {
141        java.lang.ref.FinalizerReference.add(this);
142      }
143    }
144
145    /**
146     * Creates and returns a copy of this {@code Object}. The default
147     * implementation returns a so-called "shallow" copy: It creates a new
148     * instance of the same class and then copies the field values (including
149     * object references) from this instance to the new instance. A "deep" copy,
150     * in contrast, would also recursively clone nested objects. A subclass that
151     * needs to implement this kind of cloning should call {@code super.clone()}
152     * to create the new instance and then create deep copies of the nested,
153     * mutable objects.
154     *
155     * @return a copy of this object.
156     * @throws CloneNotSupportedException
157     *             if this object's class does not implement the {@code
158     *             Cloneable} interface.
159     */
160    protected Object clone() throws CloneNotSupportedException {
161        if (!(this instanceof Cloneable)) {
162            throw new CloneNotSupportedException("Class " + getClass().getName() +
163                                                 " doesn't implement Cloneable");
164        }
165
166        return internalClone();
167    }
168
169    /*
170     * Native helper method for cloning.
171     */
172    private native Object internalClone();
173
174    /**
175     * Compares this instance with the specified object and indicates if they
176     * are equal. In order to be equal, {@code o} must represent the same object
177     * as this instance using a class-specific comparison. The general contract
178     * is that this comparison should be reflexive, symmetric, and transitive.
179     * Also, no object reference other than null is equal to null.
180     *
181     * <p>The default implementation returns {@code true} only if {@code this ==
182     * o}. See <a href="{@docRoot}reference/java/lang/Object.html#writing_equals">Writing a correct
183     * {@code equals} method</a>
184     * if you intend implementing your own {@code equals} method.
185     *
186     * <p>The general contract for the {@code equals} and {@link
187     * #hashCode()} methods is that if {@code equals} returns {@code true} for
188     * any two objects, then {@code hashCode()} must return the same value for
189     * these objects. This means that subclasses of {@code Object} usually
190     * override either both methods or neither of them.
191     *
192     * @param o
193     *            the object to compare this instance with.
194     * @return {@code true} if the specified object is equal to this {@code
195     *         Object}; {@code false} otherwise.
196     * @see #hashCode
197     */
198    public boolean equals(Object o) {
199        return this == o;
200    }
201
202    /**
203     * Invoked when the garbage collector has detected that this instance is no longer reachable.
204     * The default implementation does nothing, but this method can be overridden to free resources.
205     *
206     * <p>Note that objects that override {@code finalize} are significantly more expensive than
207     * objects that don't. Finalizers may be run a long time after the object is no longer
208     * reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
209     * Note also that finalizers are run on a single VM-wide finalizer thread,
210     * so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
211     * for a class that has a native peer and needs to call a native method to destroy that peer.
212     * Even then, it's better to provide an explicit {@code close} method (and implement
213     * {@link java.io.Closeable}), and insist that callers manually dispose of instances. This
214     * works well for something like files, but less well for something like a {@code BigInteger}
215     * where typical calling code would have to deal with lots of temporaries. Unfortunately,
216     * code that creates lots of temporaries is the worst kind of code from the point of view of
217     * the single finalizer thread.
218     *
219     * <p>If you <i>must</i> use finalizers, consider at least providing your own
220     * {@link java.lang.ref.ReferenceQueue} and having your own thread process that queue.
221     *
222     * <p>Unlike constructors, finalizers are not automatically chained. You are responsible for
223     * calling {@code super.finalize()} yourself.
224     *
225     * <p>Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer
226     * thread.
227     *
228     * See <i>Effective Java</i> Item 7, "Avoid finalizers" for more.
229     */
230    @FindBugsSuppressWarnings("FI_EMPTY")
231    protected void finalize() throws Throwable {
232    }
233
234    /**
235     * Returns the unique instance of {@link Class} that represents this
236     * object's class. Note that {@code getClass()} is a special case in that it
237     * actually returns {@code Class<? extends Foo>} where {@code Foo} is the
238     * erasure of the type of the expression {@code getClass()} was called upon.
239     * <p>
240     * As an example, the following code actually compiles, although one might
241     * think it shouldn't:
242     * <p>
243     * <pre>{@code
244     *   List<Integer> l = new ArrayList<Integer>();
245     *   Class<? extends List> c = l.getClass();}</pre>
246     *
247     * @return this object's {@code Class} instance.
248     */
249    public final Class<?> getClass() {
250      return shadow$_klass_;
251    }
252
253    /**
254     * Returns an integer hash code for this object. By contract, any two
255     * objects for which {@link #equals} returns {@code true} must return
256     * the same hash code value. This means that subclasses of {@code Object}
257     * usually override both methods or neither method.
258     *
259     * <p>Note that hash values must not change over time unless information used in equals
260     * comparisons also changes.
261     *
262     * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_hashCode">Writing a correct
263     * {@code hashCode} method</a>
264     * if you intend implementing your own {@code hashCode} method.
265     *
266     * @return this object's hash code.
267     * @see #equals
268     */
269    public int hashCode() {
270        return System.identityHashCode(this);
271    }
272
273    /**
274     * Causes a thread which is waiting on this object's monitor (by means of
275     * calling one of the {@code wait()} methods) to be woken up. If more than
276     * one thread is waiting, one of them is chosen at the discretion of the
277     * VM. The chosen thread will not run immediately. The thread
278     * that called {@code notify()} has to release the object's monitor first.
279     * Also, the chosen thread still has to compete against other threads that
280     * try to synchronize on the same object.
281     * <p>
282     * This method can only be invoked by a thread which owns this object's
283     * monitor. A thread becomes owner of an object's monitor
284     * </p>
285     * <ul>
286     * <li>by executing a synchronized method of that object;</li>
287     * <li>by executing the body of a {@code synchronized} statement that
288     * synchronizes on the object;</li>
289     * <li>by executing a synchronized static method if the object is of type
290     * {@code Class}.</li>
291     * </ul>
292     *
293     * @see #notifyAll
294     * @see #wait()
295     * @see #wait(long)
296     * @see #wait(long,int)
297     * @see java.lang.Thread
298     */
299    public final native void notify();
300
301    /**
302     * Causes all threads which are waiting on this object's monitor (by means
303     * of calling one of the {@code wait()} methods) to be woken up. The threads
304     * will not run immediately. The thread that called {@code notify()} has to
305     * release the object's monitor first. Also, the threads still have to
306     * compete against other threads that try to synchronize on the same object.
307     * <p>
308     * This method can only be invoked by a thread which owns this object's
309     * monitor. A thread becomes owner of an object's monitor
310     * </p>
311     * <ul>
312     * <li>by executing a synchronized method of that object;</li>
313     * <li>by executing the body of a {@code synchronized} statement that
314     * synchronizes on the object;</li>
315     * <li>by executing a synchronized static method if the object is of type
316     * {@code Class}.</li>
317     * </ul>
318     *
319     * @throws IllegalMonitorStateException
320     *             if the thread calling this method is not the owner of this
321     *             object's monitor.
322     * @see #notify
323     * @see #wait()
324     * @see #wait(long)
325     * @see #wait(long,int)
326     * @see java.lang.Thread
327     */
328    public final native void notifyAll();
329
330    /**
331     * Returns a string containing a concise, human-readable description of this
332     * object. Subclasses are encouraged to override this method and provide an
333     * implementation that takes into account the object's type and data. The
334     * default implementation is equivalent to the following expression:
335     * <pre>
336     *   getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>
337     * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_toString">Writing a useful
338     * {@code toString} method</a>
339     * if you intend implementing your own {@code toString} method.
340     *
341     * @return a printable representation of this object.
342     */
343    public String toString() {
344        return getClass().getName() + '@' + Integer.toHexString(hashCode());
345    }
346
347    /**
348     * Causes the calling thread to wait until another thread calls the {@code
349     * notify()} or {@code notifyAll()} method of this object. This method can
350     * only be invoked by a thread which owns this object's monitor; see
351     * {@link #notify()} on how a thread can become the owner of a monitor.
352     * <p>
353     * A waiting thread can be sent {@code interrupt()} to cause it to
354     * prematurely stop waiting, so {@code wait} should be called in a loop to
355     * check that the condition that has been waited for has been met before
356     * continuing.
357     * </p>
358     * <p>
359     * While the thread waits, it gives up ownership of this object's monitor.
360     * When it is notified (or interrupted), it re-acquires the monitor before
361     * it starts running.
362     * </p>
363     *
364     * @throws IllegalMonitorStateException
365     *             if the thread calling this method is not the owner of this
366     *             object's monitor.
367     * @throws InterruptedException
368     *             if another thread interrupts this thread while it is waiting.
369     * @see #notify
370     * @see #notifyAll
371     * @see #wait(long)
372     * @see #wait(long,int)
373     * @see java.lang.Thread
374     */
375    public final native void wait() throws InterruptedException;
376
377    /**
378     * Causes the calling thread to wait until another thread calls the {@code
379     * notify()} or {@code notifyAll()} method of this object or until the
380     * specified timeout expires. This method can only be invoked by a thread
381     * which owns this object's monitor; see {@link #notify()} on how a thread
382     * can become the owner of a monitor.
383     * <p>
384     * A waiting thread can be sent {@code interrupt()} to cause it to
385     * prematurely stop waiting, so {@code wait} should be called in a loop to
386     * check that the condition that has been waited for has been met before
387     * continuing.
388     * </p>
389     * <p>
390     * While the thread waits, it gives up ownership of this object's monitor.
391     * When it is notified (or interrupted), it re-acquires the monitor before
392     * it starts running.
393     * </p>
394     *
395     * @param millis
396     *            the maximum time to wait in milliseconds.
397     * @throws IllegalArgumentException
398     *             if {@code millis < 0}.
399     * @throws IllegalMonitorStateException
400     *             if the thread calling this method is not the owner of this
401     *             object's monitor.
402     * @throws InterruptedException
403     *             if another thread interrupts this thread while it is waiting.
404     * @see #notify
405     * @see #notifyAll
406     * @see #wait()
407     * @see #wait(long,int)
408     * @see java.lang.Thread
409     */
410    public final void wait(long millis) throws InterruptedException {
411        wait(millis, 0);
412    }
413
414    /**
415     * Causes the calling thread to wait until another thread calls the {@code
416     * notify()} or {@code notifyAll()} method of this object or until the
417     * specified timeout expires. This method can only be invoked by a thread
418     * that owns this object's monitor; see {@link #notify()} on how a thread
419     * can become the owner of a monitor.
420     * <p>
421     * A waiting thread can be sent {@code interrupt()} to cause it to
422     * prematurely stop waiting, so {@code wait} should be called in a loop to
423     * check that the condition that has been waited for has been met before
424     * continuing.
425     * </p>
426     * <p>
427     * While the thread waits, it gives up ownership of this object's monitor.
428     * When it is notified (or interrupted), it re-acquires the monitor before
429     * it starts running.
430     * </p>
431     *
432     * @param millis
433     *            the maximum time to wait in milliseconds.
434     * @param nanos
435     *            the fraction of a millisecond to wait, specified in
436     *            nanoseconds.
437     * @throws IllegalArgumentException
438     *             if {@code millis < 0}, {@code nanos < 0} or {@code nanos >
439     *             999999}.
440     * @throws IllegalMonitorStateException
441     *             if the thread calling this method is not the owner of this
442     *             object's monitor.
443     * @throws InterruptedException
444     *             if another thread interrupts this thread while it is waiting.
445     * @see #notify
446     * @see #notifyAll
447     * @see #wait()
448     * @see #wait(long,int)
449     * @see java.lang.Thread
450     */
451    public final native void wait(long millis, int nanos) throws InterruptedException;
452}
453