Object.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /* java.lang.Object - The universal superclass in Java
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.lang;
  33. /**
  34. * Object is the ultimate superclass of every class
  35. * (excepting interfaces). When you define a class that
  36. * does not extend any other class, it implicitly extends
  37. * java.lang.Object. Also, an anonymous class based on
  38. * an interface will extend Object.
  39. *
  40. * <p>It provides general-purpose methods that every single
  41. * Object, regardless of race, sex or creed, implements.
  42. * All of the public methods may be invoked on arrays or
  43. * interfaces. The protected methods <code>clone</code>
  44. * and <code>finalize</code> are not accessible on arrays
  45. * or interfaces, but all array types have a public version
  46. * of <code>clone</code> which is accessible.
  47. *
  48. * @author John Keiser
  49. * @author Eric Blake (ebb9@email.byu.edu)
  50. * @author Tom Tromey (tromey@cygnus.com)
  51. */
  52. public class Object
  53. {
  54. // WARNING: Object is a CORE class in the bootstrap cycle. See the comments
  55. // in vm/reference/java/lang/Runtime for implications of this fact.
  56. // Many JVMs do not allow for static initializers in this class,
  57. // hence we do not use them in the default implementation.
  58. // Some VM's rely on the order that these methods appear when laying
  59. // out their internal structure. Therefore, do not haphazardly
  60. // rearrange these methods.
  61. /**
  62. * The basic constructor. Object is special, because it has no
  63. * superclass, so there is no call to super().
  64. *
  65. * @throws OutOfMemoryError Technically, this constructor never
  66. * throws an OutOfMemoryError, because the memory has
  67. * already been allocated by this point. But as all
  68. * instance creation expressions eventually trace back
  69. * to this constructor, and creating an object allocates
  70. * memory, we list that possibility here.
  71. */
  72. // This could be implicit, but then javadoc would not document it!
  73. public Object() {}
  74. /**
  75. * Determine whether this Object is semantically equal
  76. * to another Object.
  77. *
  78. * <p>There are some fairly strict requirements on this
  79. * method which subclasses must follow:<br>
  80. * <ul>
  81. * <li>It must be transitive. If <code>a.equals(b)</code> and
  82. * <code>b.equals(c)</code>, then <code>a.equals(c)</code>
  83. * must be true as well.</li>
  84. * <li>It must be symmetric. <code>a.equals(b)</code> and
  85. * <code>b.equals(a)</code> must have the same value.</li>
  86. * <li>It must be reflexive. <code>a.equals(a)</code> must
  87. * always be true.</li>
  88. * <li>It must be consistent. Whichever value a.equals(b)
  89. * returns on the first invocation must be the value
  90. * returned on all later invocations.</li>
  91. * <li><code>a.equals(null)</code> must be false.</li>
  92. * <li>It must be consistent with hashCode(). That is,
  93. * <code>a.equals(b)</code> must imply
  94. * <code>a.hashCode() == b.hashCode()</code>.
  95. * The reverse is not true; two objects that are not
  96. * equal may have the same hashcode, but that has
  97. * the potential to harm hashing performance.</li>
  98. * </ul>
  99. *
  100. * <p>This is typically overridden to throw a {@link ClassCastException}
  101. * if the argument is not comparable to the class performing
  102. * the comparison, but that is not a requirement. It is legal
  103. * for <code>a.equals(b)</code> to be true even though
  104. * <code>a.getClass() != b.getClass()</code>. Also, it
  105. * is typical to never cause a {@link NullPointerException}.
  106. *
  107. * <p>In general, the Collections API ({@link java.util}) use the
  108. * <code>equals</code> method rather than the <code>==</code>
  109. * operator to compare objects. However, {@link java.util.IdentityHashMap}
  110. * is an exception to this rule, for its own good reasons.
  111. *
  112. * <p>The default implementation returns <code>this == o</code>.
  113. *
  114. * @param obj the Object to compare to
  115. * @return whether this Object is semantically equal to another
  116. * @see #hashCode()
  117. */
  118. public boolean equals(Object obj)
  119. {
  120. return this == obj;
  121. }
  122. /**
  123. * Get a value that represents this Object, as uniquely as
  124. * possible within the confines of an int.
  125. *
  126. * <p>There are some requirements on this method which
  127. * subclasses must follow:<br>
  128. *
  129. * <ul>
  130. * <li>Semantic equality implies identical hashcodes. In other
  131. * words, if <code>a.equals(b)</code> is true, then
  132. * <code>a.hashCode() == b.hashCode()</code> must be as well.
  133. * However, the reverse is not necessarily true, and two
  134. * objects may have the same hashcode without being equal.</li>
  135. * <li>It must be consistent. Whichever value o.hashCode()
  136. * returns on the first invocation must be the value
  137. * returned on all later invocations as long as the object
  138. * exists. Notice, however, that the result of hashCode may
  139. * change between separate executions of a Virtual Machine,
  140. * because it is not invoked on the same object.</li>
  141. * </ul>
  142. *
  143. * <p>Notice that since <code>hashCode</code> is used in
  144. * {@link java.util.Hashtable} and other hashing classes,
  145. * a poor implementation will degrade the performance of hashing
  146. * (so don't blindly implement it as returning a constant!). Also,
  147. * if calculating the hash is time-consuming, a class may consider
  148. * caching the results.
  149. *
  150. * <p>The default implementation returns
  151. * <code>System.identityHashCode(this)</code>
  152. *
  153. * @return the hash code for this Object
  154. * @see #equals(Object)
  155. * @see System#identityHashCode(Object)
  156. */
  157. public int hashCode()
  158. {
  159. return System.identityHashCode(this);
  160. }
  161. /**
  162. * Convert this Object to a human-readable String.
  163. * There are no limits placed on how long this String
  164. * should be or what it should contain. We suggest you
  165. * make it as intuitive as possible to be able to place
  166. * it into {@link java.io.PrintStream#println() System.out.println()}
  167. * and such.
  168. *
  169. * <p>It is typical, but not required, to ensure that this method
  170. * never completes abruptly with a {@link RuntimeException}.
  171. *
  172. * <p>This method will be called when performing string
  173. * concatenation with this object. If the result is
  174. * <code>null</code>, string concatenation will instead
  175. * use <code>"null"</code>.
  176. *
  177. * <p>The default implementation returns
  178. * <code>getClass().getName() + "@" +
  179. * Integer.toHexString(hashCode())</code>.
  180. *
  181. * @return the String representing this Object, which may be null
  182. * @throws OutOfMemoryError The default implementation creates a new
  183. * String object, therefore it must allocate memory
  184. * @see #getClass()
  185. * @see #hashCode()
  186. * @see Class#getName()
  187. * @see Integer#toHexString(int)
  188. */
  189. public String toString()
  190. {
  191. return getClass().getName() + '@' + Integer.toHexString(hashCode());
  192. }
  193. /**
  194. * Called on an object by the Virtual Machine at most once,
  195. * at some point after the Object is determined unreachable
  196. * but before it is destroyed. You would think that this
  197. * means it eventually is called on every Object, but this is
  198. * not necessarily the case. If execution terminates
  199. * abnormally, garbage collection does not always happen.
  200. * Thus you cannot rely on this method to always work.
  201. * For finer control over garbage collection, use references
  202. * from the {@link java.lang.ref} package.
  203. *
  204. * <p>Virtual Machines are free to not call this method if
  205. * they can determine that it does nothing important; for
  206. * example, if your class extends Object and overrides
  207. * finalize to do simply <code>super.finalize()</code>.
  208. *
  209. * <p>finalize() will be called by a {@link Thread} that has no
  210. * locks on any Objects, and may be called concurrently.
  211. * There are no guarantees on the order in which multiple
  212. * objects are finalized. This means that finalize() is
  213. * usually unsuited for performing actions that must be
  214. * thread-safe, and that your implementation must be
  215. * use defensive programming if it is to always work.
  216. *
  217. * <p>If an Exception is thrown from finalize() during garbage
  218. * collection, it will be patently ignored and the Object will
  219. * still be destroyed.
  220. *
  221. * <p>It is allowed, although not typical, for user code to call
  222. * finalize() directly. User invocation does not affect whether
  223. * automatic invocation will occur. It is also permitted,
  224. * although not recommended, for a finalize() method to "revive"
  225. * an object by making it reachable from normal code again.
  226. *
  227. * <p>Unlike constructors, finalize() does not get called
  228. * for an object's superclass unless the implementation
  229. * specifically calls <code>super.finalize()</code>.
  230. *
  231. * <p>The default implementation does nothing.
  232. *
  233. * @throws Throwable permits a subclass to throw anything in an
  234. * overridden version; but the default throws nothing
  235. * @see System#gc()
  236. * @see System#runFinalizersOnExit(boolean)
  237. * @see java.lang.ref
  238. */
  239. protected void finalize() throws Throwable
  240. {
  241. }
  242. /**
  243. * This method may be called to create a new copy of the
  244. * Object. The typical behavior is as follows:<br>
  245. * <ul>
  246. * <li><code>o == o.clone()</code> is false</li>
  247. * <li><code>o.getClass() == o.clone().getClass()</code>
  248. * is true</li>
  249. * <li><code>o.equals(o)</code> is true</li>
  250. * </ul>
  251. *
  252. * <p>However, these are not strict requirements, and may
  253. * be violated if necessary. Of the three requirements, the
  254. * last is the most commonly violated, particularly if the
  255. * subclass does not override {@link #equals(Object)}.
  256. *
  257. * <p>If the Object you call clone() on does not implement
  258. * {@link Cloneable} (which is a placeholder interface), then
  259. * a CloneNotSupportedException is thrown. Notice that
  260. * Object does not implement Cloneable; this method exists
  261. * as a convenience for subclasses that do.
  262. *
  263. * <p>Object's implementation of clone allocates space for the
  264. * new Object using the correct class, without calling any
  265. * constructors, and then fills in all of the new field values
  266. * with the old field values. Thus, it is a shallow copy.
  267. * However, subclasses are permitted to make a deep copy.
  268. *
  269. * <p>All array types implement Cloneable, and override
  270. * this method as follows (it should never fail):<br>
  271. * <pre>
  272. * public Object clone()
  273. * {
  274. * try
  275. * {
  276. * super.clone();
  277. * }
  278. * catch (CloneNotSupportedException e)
  279. * {
  280. * throw new InternalError(e.getMessage());
  281. * }
  282. * }
  283. * </pre>
  284. *
  285. * @return a copy of the Object
  286. * @throws CloneNotSupportedException If this Object does not
  287. * implement Cloneable
  288. * @throws OutOfMemoryError Since cloning involves memory allocation,
  289. * even though it may bypass constructors, you might run
  290. * out of memory
  291. * @see Cloneable
  292. */
  293. protected Object clone() throws CloneNotSupportedException
  294. {
  295. if (this instanceof Cloneable)
  296. return VMObject.clone((Cloneable) this);
  297. throw new CloneNotSupportedException("Object not cloneable");
  298. }
  299. /**
  300. * Returns the runtime {@link Class} of this Object.
  301. *
  302. * <p>The class object can also be obtained without a runtime
  303. * instance by using the class literal, as in:
  304. * <code>Foo.class</code>. Notice that the class literal
  305. * also works on primitive types, making it useful for
  306. * reflection purposes.
  307. *
  308. * @return the class of this Object
  309. */
  310. public final Class<? extends Object> getClass()
  311. {
  312. return VMObject.getClass(this);
  313. }
  314. /**
  315. * Wakes up one of the {@link Thread}s that has called
  316. * <code>wait</code> on this Object. Only the owner
  317. * of a lock on this Object may call this method. This lock
  318. * is obtained by a <code>synchronized</code> method or statement.
  319. *
  320. * <p>The Thread to wake up is chosen arbitrarily. The
  321. * awakened thread is not guaranteed to be the next thread
  322. * to actually obtain the lock on this object.
  323. *
  324. * <p>This thread still holds a lock on the object, so it is
  325. * typical to release the lock by exiting the synchronized
  326. * code, calling wait(), or calling {@link Thread#sleep(long)}, so
  327. * that the newly awakened thread can actually resume. The
  328. * awakened thread will most likely be awakened with an
  329. * {@link InterruptedException}, but that is not guaranteed.
  330. *
  331. * @throws IllegalMonitorStateException if this Thread
  332. * does not own the lock on the Object
  333. * @see #notifyAll()
  334. * @see #wait()
  335. * @see #wait(long)
  336. * @see #wait(long, int)
  337. * @see Thread
  338. */
  339. public final void notify() throws IllegalMonitorStateException
  340. {
  341. VMObject.notify(this);
  342. }
  343. /**
  344. * Wakes up all of the {@link Thread}s that have called
  345. * <code>wait</code> on this Object. Only the owner
  346. * of a lock on this Object may call this method. This lock
  347. * is obtained by a <code>synchronized</code> method or statement.
  348. *
  349. * <p>There are no guarantees as to which thread will next
  350. * obtain the lock on the object.
  351. *
  352. * <p>This thread still holds a lock on the object, so it is
  353. * typical to release the lock by exiting the synchronized
  354. * code, calling wait(), or calling {@link Thread#sleep(long)}, so
  355. * that one of the newly awakened threads can actually resume.
  356. * The resuming thread will most likely be awakened with an
  357. * {@link InterruptedException}, but that is not guaranteed.
  358. *
  359. * @throws IllegalMonitorStateException if this Thread
  360. * does not own the lock on the Object
  361. * @see #notify()
  362. * @see #wait()
  363. * @see #wait(long)
  364. * @see #wait(long, int)
  365. * @see Thread
  366. */
  367. public final void notifyAll() throws IllegalMonitorStateException
  368. {
  369. VMObject.notifyAll(this);
  370. }
  371. /**
  372. * Waits indefinitely for notify() or notifyAll() to be
  373. * called on the Object in question. Implementation is
  374. * identical to wait(0).
  375. *
  376. * <p>The Thread that calls wait must have a lock on this Object,
  377. * obtained by a <code>synchronized</code> method or statement.
  378. * After calling wait, the thread loses the lock on this
  379. * object until the method completes (abruptly or normally),
  380. * at which time it regains the lock. All locks held on
  381. * other objects remain in force, even though the thread is
  382. * inactive. Therefore, caution must be used to avoid deadlock.
  383. *
  384. * <p>While it is typical that this method will complete abruptly
  385. * with an {@link InterruptedException}, it is not guaranteed. So,
  386. * it is typical to call wait inside an infinite loop:<br>
  387. *
  388. * <pre>
  389. * try
  390. * {
  391. * while (true)
  392. * lock.wait();
  393. * }
  394. * catch (InterruptedException e)
  395. * {
  396. * }
  397. * </pre>
  398. *
  399. * @throws IllegalMonitorStateException if this Thread
  400. * does not own a lock on this Object
  401. * @throws InterruptedException if some other Thread
  402. * interrupts this Thread
  403. * @see #notify()
  404. * @see #notifyAll()
  405. * @see #wait(long)
  406. * @see #wait(long, int)
  407. * @see Thread
  408. */
  409. public final void wait()
  410. throws IllegalMonitorStateException, InterruptedException
  411. {
  412. VMObject.wait(this, 0, 0);
  413. }
  414. /**
  415. * Waits a specified amount of time (or indefinitely if
  416. * the time specified is 0) for someone to call notify()
  417. * or notifyAll() on this Object, waking up this Thread.
  418. *
  419. * <p>The Thread that calls wait must have a lock on this Object,
  420. * obtained by a <code>synchronized</code> method or statement.
  421. * After calling wait, the thread loses the lock on this
  422. * object until the method completes (abruptly or normally),
  423. * at which time it regains the lock. All locks held on
  424. * other objects remain in force, even though the thread is
  425. * inactive. Therefore, caution must be used to avoid deadlock.
  426. *
  427. * <p>Usually, this call will complete normally if the time
  428. * expires, or abruptly with {@link InterruptedException}
  429. * if another thread called notify, but neither result
  430. * is guaranteed.
  431. *
  432. * <p>The waiting period is only *roughly* the amount of time
  433. * you requested. It cannot be exact because of the overhead
  434. * of the call itself. Most Virtual Machiness treat the
  435. * argument as a lower limit on the time spent waiting, but
  436. * even that is not guaranteed. Besides, some other thread
  437. * may hold the lock on the object when the time expires, so
  438. * the current thread may still have to wait to reobtain the
  439. * lock.
  440. *
  441. * @param ms the minimum number of milliseconds to wait (1000
  442. * milliseconds = 1 second), or 0 for an indefinite wait
  443. * @throws IllegalArgumentException if ms &lt; 0
  444. * @throws IllegalMonitorStateException if this Thread
  445. * does not own a lock on this Object
  446. * @throws InterruptedException if some other Thread
  447. * interrupts this Thread
  448. * @see #notify()
  449. * @see #notifyAll()
  450. * @see #wait()
  451. * @see #wait(long, int)
  452. * @see Thread
  453. */
  454. public final void wait(long ms)
  455. throws IllegalMonitorStateException, InterruptedException
  456. {
  457. wait(ms, 0);
  458. }
  459. /**
  460. * Waits a specified amount of time (or indefinitely if
  461. * the time specified is 0) for someone to call notify()
  462. * or notifyAll() on this Object, waking up this Thread.
  463. *
  464. * <p>The Thread that calls wait must have a lock on this Object,
  465. * obtained by a <code>synchronized</code> method or statement.
  466. * After calling wait, the thread loses the lock on this
  467. * object until the method completes (abruptly or normally),
  468. * at which time it regains the lock. All locks held on
  469. * other objects remain in force, even though the thread is
  470. * inactive. Therefore, caution must be used to avoid deadlock.
  471. *
  472. * <p>Usually, this call will complete normally if the time
  473. * expires, or abruptly with {@link InterruptedException}
  474. * if another thread called notify, but neither result
  475. * is guaranteed.
  476. *
  477. * <p>The waiting period is nowhere near as precise as
  478. * nanoseconds; considering that even wait(int) is inaccurate,
  479. * how much can you expect? But on supporting
  480. * implementations, this offers somewhat more granularity
  481. * than milliseconds.
  482. *
  483. * @param ms the number of milliseconds to wait (1,000
  484. * milliseconds = 1 second)
  485. * @param ns the number of nanoseconds to wait over and
  486. * above ms (1,000,000 nanoseconds = 1 millisecond)
  487. * @throws IllegalArgumentException if ms &lt; 0 or ns is not
  488. * in the range 0 to 999,999
  489. * @throws IllegalMonitorStateException if this Thread
  490. * does not own a lock on this Object
  491. * @throws InterruptedException if some other Thread
  492. * interrupts this Thread
  493. * @see #notify()
  494. * @see #notifyAll()
  495. * @see #wait()
  496. * @see #wait(long)
  497. * @see Thread
  498. */
  499. public final void wait(long ms, int ns)
  500. throws IllegalMonitorStateException, InterruptedException
  501. {
  502. if (ms < 0 || ns < 0 || ns > 999999)
  503. throw new IllegalArgumentException("argument out of range");
  504. VMObject.wait(this, ms, ns);
  505. }
  506. } // class Object