1 /* 2 * Copyright (c) 1994, 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import jdk.internal.vm.annotation.IntrinsicCandidate; 29 30 /** 31 * Class {@code Object} is the root of the class hierarchy. 32 * Every class has {@code Object} as a superclass. All objects, 33 * including arrays, implement the methods of this class. 34 * <p> 35 * Subclasses of {@code java.lang.Object} can be either an {@linkplain Class#isIdentity identity class} 36 * or a {@linkplain Class#isValue value class}. 37 * See {@jls The Java Language Specification 8.1.1.5 Value Classes}. 38 * 39 * @see java.lang.Class 40 * @since 1.0 41 */ 42 public class Object { 43 44 /** 45 * Constructs a new object. 46 */ 47 @IntrinsicCandidate 48 public Object() {} 49 50 /** 51 * Returns the runtime class of this {@code Object}. The returned 52 * {@code Class} object is the object that is locked by {@code 53 * static synchronized} methods of the represented class. 54 * 55 * <p><b>The actual result type is {@code Class<? extends |X|>} 56 * where {@code |X|} is the erasure of the static type of the 57 * expression on which {@code getClass} is called.</b> For 58 * example, no cast is required in this code fragment:</p> 59 * 60 * <p> 61 * {@code Number n = 0; }<br> 62 * {@code Class<? extends Number> c = n.getClass(); } 63 * </p> 64 * 65 * @return The {@code Class} object that represents the runtime 66 * class of this object. 67 * @jls 15.8.2 Class Literals 68 */ 69 @IntrinsicCandidate 70 public final native Class<?> getClass(); 71 72 /** 73 * {@return a hash code value for this object} This method is 74 * supported for the benefit of hash tables such as those provided by 75 * {@link java.util.HashMap}. 76 * <p> 77 * The general contract of {@code hashCode} is: 78 * <ul> 79 * <li>Whenever it is invoked on the same object more than once during 80 * an execution of a Java application, the {@code hashCode} method 81 * must consistently return the same integer, provided no information 82 * used in {@code equals} comparisons on the object is modified. 83 * This integer need not remain consistent from one execution of an 84 * application to another execution of the same application. 85 * <li>If two objects are equal according to the {@link 86 * #equals(Object) equals} method, then calling the {@code 87 * hashCode} method on each of the two objects must produce the 88 * same integer result. 89 * <li>It is <em>not</em> required that if two objects are unequal 90 * according to the {@link #equals(Object) equals} method, then 91 * calling the {@code hashCode} method on each of the two objects 92 * must produce distinct integer results. However, the programmer 93 * should be aware that producing distinct integer results for 94 * unequal objects may improve the performance of hash tables. 95 * </ul> 96 * 97 * @implSpec 98 * As far as is reasonably practical, the {@code hashCode} method defined 99 * by class {@code Object} returns distinct integers for distinct objects. 100 * 101 * @apiNote 102 * The {@link java.util.Objects#hash(Object...) hash} and {@link 103 * java.util.Objects#hashCode(Object) hashCode} methods of {@link 104 * java.util.Objects} can be used to help construct simple hash codes. 105 * 106 * @see java.lang.Object#equals(java.lang.Object) 107 * @see java.lang.System#identityHashCode 108 */ 109 @IntrinsicCandidate 110 public native int hashCode(); 111 112 /** 113 * Indicates whether some other object is "equal to" this one. 114 * <p> 115 * The {@code equals} method implements an <dfn>{@index "equivalence relation"}</dfn> 116 * on non-null object references: 117 * <ul> 118 * <li>It is <i>reflexive</i>: for any non-null reference value 119 * {@code x}, {@code x.equals(x)} should return 120 * {@code true}. 121 * <li>It is <i>symmetric</i>: for any non-null reference values 122 * {@code x} and {@code y}, {@code x.equals(y)} 123 * should return {@code true} if and only if 124 * {@code y.equals(x)} returns {@code true}. 125 * <li>It is <i>transitive</i>: for any non-null reference values 126 * {@code x}, {@code y}, and {@code z}, if 127 * {@code x.equals(y)} returns {@code true} and 128 * {@code y.equals(z)} returns {@code true}, then 129 * {@code x.equals(z)} should return {@code true}. 130 * <li>It is <i>consistent</i>: for any non-null reference values 131 * {@code x} and {@code y}, multiple invocations of 132 * {@code x.equals(y)} consistently return {@code true} 133 * or consistently return {@code false}, provided no 134 * information used in {@code equals} comparisons on the 135 * objects is modified. 136 * <li>For any non-null reference value {@code x}, 137 * {@code x.equals(null)} should return {@code false}. 138 * </ul> 139 * 140 * <p> 141 * An equivalence relation partitions the elements it operates on 142 * into <i>equivalence classes</i>; all the members of an 143 * equivalence class are equal to each other. Members of an 144 * equivalence class are substitutable for each other, at least 145 * for some purposes. 146 * 147 * @implSpec 148 * The {@code equals} method for class {@code Object} implements 149 * the most discriminating possible equivalence relation on objects; 150 * that is, for any non-null reference values {@code x} and 151 * {@code y}, this method returns {@code true} if and only 152 * if {@code x} and {@code y} refer to the same object 153 * ({@code x == y} has the value {@code true}). 154 * 155 * In other words, under the reference equality equivalence 156 * relation, each equivalence class only has a single element. 157 * 158 * @apiNote 159 * It is generally necessary to override the {@link #hashCode() hashCode} 160 * method whenever this method is overridden, so as to maintain the 161 * general contract for the {@code hashCode} method, which states 162 * that equal objects must have equal hash codes. 163 * <p>The two-argument {@link java.util.Objects#equals(Object, 164 * Object) Objects.equals} method implements an equivalence relation 165 * on two possibly-null object references. 166 * 167 * @param obj the reference object with which to compare. 168 * @return {@code true} if this object is the same as the obj 169 * argument; {@code false} otherwise. 170 * @see #hashCode() 171 * @see java.util.HashMap 172 */ 173 public boolean equals(Object obj) { 174 return (this == obj); 175 } 176 177 /** 178 * Creates and returns a copy of this object. The precise meaning 179 * of "copy" may depend on the class of the object. The general 180 * intent is that, for any object {@code x}, the expression: 181 * <blockquote> 182 * <pre> 183 * x.clone() != x</pre></blockquote> 184 * will be true, and that the expression: 185 * <blockquote> 186 * <pre> 187 * x.clone().getClass() == x.getClass()</pre></blockquote> 188 * will be {@code true}, but these are not absolute requirements. 189 * While it is typically the case that: 190 * <blockquote> 191 * <pre> 192 * x.clone().equals(x)</pre></blockquote> 193 * will be {@code true}, this is not an absolute requirement. 194 * <p> 195 * By convention, the returned object should be obtained by calling 196 * {@code super.clone}. If a class and all of its superclasses (except 197 * {@code Object}) obey this convention, it will be the case that 198 * {@code x.clone().getClass() == x.getClass()}. 199 * <p> 200 * By convention, the object returned by this method should be independent 201 * of this object (which is being cloned). To achieve this independence, 202 * it may be necessary to modify one or more fields of the object returned 203 * by {@code super.clone} before returning it. Typically, this means 204 * copying any mutable objects that comprise the internal "deep structure" 205 * of the object being cloned and replacing the references to these 206 * objects with references to the copies. If a class contains only 207 * primitive fields or references to immutable objects, then it is usually 208 * the case that no fields in the object returned by {@code super.clone} 209 * need to be modified. 210 * 211 * @implSpec 212 * The method {@code clone} for class {@code Object} performs a 213 * specific cloning operation. First, if the class of this object does 214 * not implement the interface {@code Cloneable}, then a 215 * {@code CloneNotSupportedException} is thrown. Note that all arrays 216 * are considered to implement the interface {@code Cloneable} and that 217 * the return type of the {@code clone} method of an array type {@code T[]} 218 * is {@code T[]} where T is any reference or primitive type. 219 * Otherwise, this method creates a new instance of the class of this 220 * object and initializes all its fields with exactly the contents of 221 * the corresponding fields of this object, as if by assignment; the 222 * contents of the fields are not themselves cloned. Thus, this method 223 * performs a "shallow copy" of this object, not a "deep copy" operation. 224 * <p> 225 * The class {@code Object} does not itself implement the interface 226 * {@code Cloneable}, so calling the {@code clone} method on an object 227 * whose class is {@code Object} will result in throwing an 228 * exception at run time. 229 * 230 * @return a clone of this instance. 231 * @throws CloneNotSupportedException if the object's class does not 232 * support the {@code Cloneable} interface. Subclasses 233 * that override the {@code clone} method can also 234 * throw this exception to indicate that an instance cannot 235 * be cloned. 236 * @see java.lang.Cloneable 237 */ 238 @IntrinsicCandidate 239 protected native Object clone() throws CloneNotSupportedException; 240 241 /** 242 * {@return a string representation of the object} 243 * 244 * Satisfying this method's contract implies a non-{@code null} 245 * result must be returned. 246 * 247 * @apiNote 248 * In general, the 249 * {@code toString} method returns a string that 250 * "textually represents" this object. The result should 251 * be a concise but informative representation that is easy for a 252 * person to read. 253 * It is recommended that all subclasses override this method. 254 * The string output is not necessarily stable over time or across 255 * JVM invocations. 256 * @implSpec 257 * The {@code toString} method for class {@code Object} 258 * returns a string consisting of the name of the class of which the 259 * object is an instance, the at-sign character `{@code @}', and 260 * the unsigned hexadecimal representation of the hash code of the 261 * object. In other words, this method returns a string equal to the 262 * value of: 263 * {@snippet lang=java : 264 * getClass().getName() + '@' + Integer.toHexString(hashCode()) 265 * } 266 * The {@link java.util.Objects#toIdentityString(Object) 267 * Objects.toIdentityString} method returns the string for an 268 * object equal to the string that would be returned if neither 269 * the {@code toString} nor {@code hashCode} methods were 270 * overridden by the object's class. 271 */ 272 public String toString() { 273 return getClass().getName() + "@" + Integer.toHexString(hashCode()); 274 } 275 276 /** 277 * Wakes up a single thread that is waiting on this object's 278 * monitor. If any threads are waiting on this object, one of them 279 * is chosen to be awakened. The choice is arbitrary and occurs at 280 * the discretion of the implementation. A thread waits on an object's 281 * monitor by calling one of the {@code wait} methods. 282 * <p> 283 * The awakened thread will not be able to proceed until the current 284 * thread relinquishes the lock on this object. The awakened thread will 285 * compete in the usual manner with any other threads that might be 286 * actively competing to synchronize on this object; for example, the 287 * awakened thread enjoys no reliable privilege or disadvantage in being 288 * the next thread to lock this object. 289 * <p> 290 * This method should only be called by a thread that is the owner 291 * of this object's monitor. A thread becomes the owner of the 292 * object's monitor in one of three ways: 293 * <ul> 294 * <li>By executing a synchronized instance method of that object. 295 * <li>By executing the body of a {@code synchronized} statement 296 * that synchronizes on the object. 297 * <li>For objects of type {@code Class,} by executing a 298 * static synchronized method of that class. 299 * </ul> 300 * <p> 301 * Only one thread at a time can own an object's monitor. 302 * <div class="preview-block"> 303 * <div class="preview-comment"> 304 * If this object is a {@linkplain Class#isValue() value object}, 305 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown. 306 * </div> 307 * </div> 308 * 309 * @throws IllegalMonitorStateException if the current thread is not 310 * the owner of this object's monitor or 311 * if this object is a {@linkplain Class#isValue() value object}. 312 * @see java.lang.Object#notifyAll() 313 * @see java.lang.Object#wait() 314 */ 315 @IntrinsicCandidate 316 public final native void notify(); 317 318 /** 319 * Wakes up all threads that are waiting on this object's monitor. A 320 * thread waits on an object's monitor by calling one of the 321 * {@code wait} methods. 322 * <p> 323 * The awakened threads will not be able to proceed until the current 324 * thread relinquishes the lock on this object. The awakened threads 325 * will compete in the usual manner with any other threads that might 326 * be actively competing to synchronize on this object; for example, 327 * the awakened threads enjoy no reliable privilege or disadvantage in 328 * being the next thread to lock this object. 329 * <p> 330 * This method should only be called by a thread that is the owner 331 * of this object's monitor. See the {@code notify} method for a 332 * description of the ways in which a thread can become the owner of 333 * a monitor. 334 * 335 * <div class="preview-block"> 336 * <div class="preview-comment"> 337 * If this object is a {@linkplain Class#isValue() value object}, 338 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown. 339 * </div> 340 * </div> 341 * 342 * @throws IllegalMonitorStateException if the current thread is not 343 * the owner of this object's monitor or 344 * if this object is a {@linkplain Class#isValue() value object}. 345 * @see java.lang.Object#notify() 346 * @see java.lang.Object#wait() 347 */ 348 @IntrinsicCandidate 349 public final native void notifyAll(); 350 351 /** 352 * Causes the current thread to wait until it is awakened, typically 353 * by being <em>notified</em> or <em>interrupted</em>. 354 * <p> 355 * In all respects, this method behaves as if {@code wait(0L, 0)} 356 * had been called. See the specification of the {@link #wait(long, int)} method 357 * for details. 358 * 359 * <div class="preview-block"> 360 * <div class="preview-comment"> 361 * If this object is a {@linkplain Class#isValue() value object}, 362 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown. 363 * </div> 364 * </div> 365 * 366 * @throws IllegalMonitorStateException if the current thread is not 367 * the owner of the object's monitor or 368 * if this object is a {@linkplain Class#isValue() value object}. 369 * @throws InterruptedException if any thread interrupted the current thread before or 370 * while the current thread was waiting. The <em>interrupted status</em> of the 371 * current thread is cleared when this exception is thrown. 372 * @see #notify() 373 * @see #notifyAll() 374 * @see #wait(long) 375 * @see #wait(long, int) 376 */ 377 public final void wait() throws InterruptedException { 378 wait(0L); 379 } 380 381 /** 382 * Causes the current thread to wait until it is awakened, typically 383 * by being <em>notified</em> or <em>interrupted</em>, or until a 384 * certain amount of real time has elapsed. 385 * <p> 386 * In all respects, this method behaves as if {@code wait(timeoutMillis, 0)} 387 * had been called. See the specification of the {@link #wait(long, int)} method 388 * for details. 389 * 390 * <div class="preview-block"> 391 * <div class="preview-comment"> 392 * If this object is a {@linkplain Class#isValue() value object}, 393 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown. 394 * </div> 395 * </div> 396 * 397 * @param timeoutMillis the maximum time to wait, in milliseconds 398 * @throws IllegalArgumentException if {@code timeoutMillis} is negative 399 * @throws IllegalMonitorStateException if the current thread is not 400 * the owner of the object's monitor or 401 * if this object is a {@linkplain Class#isValue() value object}. 402 * @throws InterruptedException if any thread interrupted the current thread before or 403 * while the current thread was waiting. The <em>interrupted status</em> of the 404 * current thread is cleared when this exception is thrown. 405 * @see #notify() 406 * @see #notifyAll() 407 * @see #wait() 408 * @see #wait(long, int) 409 */ 410 public final void wait(long timeoutMillis) throws InterruptedException { 411 if (timeoutMillis < 0) { 412 throw new IllegalArgumentException("timeout value is negative"); 413 } 414 415 if (Thread.currentThread() instanceof VirtualThread vthread) { 416 try { 417 wait0(timeoutMillis); 418 } catch (InterruptedException e) { 419 // virtual thread's interrupt status needs to be cleared 420 vthread.getAndClearInterrupt(); 421 throw e; 422 } 423 } else { 424 wait0(timeoutMillis); 425 } 426 } 427 428 // final modifier so method not in vtable 429 private final native void wait0(long timeoutMillis) throws InterruptedException; 430 431 /** 432 * Causes the current thread to wait until it is awakened, typically 433 * by being <em>notified</em> or <em>interrupted</em>, or until a 434 * certain amount of real time has elapsed. 435 * <p> 436 * The current thread must own this object's monitor lock. See the 437 * {@link #notify notify} method for a description of the ways in which 438 * a thread can become the owner of a monitor lock. 439 * <p> 440 * This method causes the current thread (referred to here as <var>T</var>) to 441 * place itself in the wait set for this object and then to relinquish any 442 * and all synchronization claims on this object. Note that only the locks 443 * on this object are relinquished; any other objects on which the current 444 * thread may be synchronized remain locked while the thread waits. 445 * <p> 446 * Thread <var>T</var> then becomes disabled for thread scheduling purposes 447 * and lies dormant until one of the following occurs: 448 * <ul> 449 * <li>Some other thread invokes the {@code notify} method for this 450 * object and thread <var>T</var> happens to be arbitrarily chosen as 451 * the thread to be awakened. 452 * <li>Some other thread invokes the {@code notifyAll} method for this 453 * object. 454 * <li>Some other thread {@linkplain Thread#interrupt() interrupts} 455 * thread <var>T</var>. 456 * <li>The specified amount of real time has elapsed, more or less. 457 * The amount of real time, in nanoseconds, is given by the expression 458 * {@code 1000000 * timeoutMillis + nanos}. If {@code timeoutMillis} and {@code nanos} 459 * are both zero, then real time is not taken into consideration and the 460 * thread waits until awakened by one of the other causes. 461 * <li>Thread <var>T</var> is awakened spuriously. (See below.) 462 * </ul> 463 * <p> 464 * The thread <var>T</var> is then removed from the wait set for this 465 * object and re-enabled for thread scheduling. It competes in the 466 * usual manner with other threads for the right to synchronize on the 467 * object; once it has regained control of the object, all its 468 * synchronization claims on the object are restored to the status quo 469 * ante - that is, to the situation as of the time that the {@code wait} 470 * method was invoked. Thread <var>T</var> then returns from the 471 * invocation of the {@code wait} method. Thus, on return from the 472 * {@code wait} method, the synchronization state of the object and of 473 * thread {@code T} is exactly as it was when the {@code wait} method 474 * was invoked. 475 * <p> 476 * A thread can wake up without being notified, interrupted, or timing out, a 477 * so-called <em>spurious wakeup</em>. While this will rarely occur in practice, 478 * applications must guard against it by testing for the condition that should 479 * have caused the thread to be awakened, and continuing to wait if the condition 480 * is not satisfied. See the example below. 481 * <p> 482 * For more information on this topic, see section 14.2, 483 * "Condition Queues," in Brian Goetz and others' <cite>Java Concurrency 484 * in Practice</cite> (Addison-Wesley, 2006) or Item 81 in Joshua 485 * Bloch's <cite>Effective Java, Third Edition</cite> (Addison-Wesley, 486 * 2018). 487 * <p> 488 * If the current thread is {@linkplain java.lang.Thread#interrupt() interrupted} 489 * by any thread before or while it is waiting, then an {@code InterruptedException} 490 * is thrown. The <em>interrupted status</em> of the current thread is cleared when 491 * this exception is thrown. This exception is not thrown until the lock status of 492 * this object has been restored as described above. 493 * 494 * @apiNote 495 * The recommended approach to waiting is to check the condition being awaited in 496 * a {@code while} loop around the call to {@code wait}, as shown in the example 497 * below. Among other things, this approach avoids problems that can be caused 498 * by spurious wakeups. 499 * 500 * {@snippet lang=java : 501 * synchronized (obj) { 502 * while ( <condition does not hold and timeout not exceeded> ) { 503 * long timeoutMillis = ... ; // recompute timeout values 504 * int nanos = ... ; 505 * obj.wait(timeoutMillis, nanos); 506 * } 507 * ... // Perform action appropriate to condition or timeout 508 * } 509 * } 510 * 511 * <div class="preview-block"> 512 * <div class="preview-comment"> 513 * If this object is a {@linkplain Class#isValue() value object}, 514 * it does does not have a monitor, an {@code IllegalMonitorStateException} is thrown. 515 * </div> 516 * </div> 517 * @param timeoutMillis the maximum time to wait, in milliseconds 518 * @param nanos additional time, in nanoseconds, in the range 0-999999 inclusive 519 * @throws IllegalArgumentException if {@code timeoutMillis} is negative, 520 * or if the value of {@code nanos} is out of range 521 * @throws IllegalMonitorStateException if the current thread is not 522 * the owner of the object's monitor or 523 * if this object is a {@linkplain Class#isValue() value object}. 524 * @throws InterruptedException if any thread interrupted the current thread before or 525 * while the current thread was waiting. The <em>interrupted status</em> of the 526 * current thread is cleared when this exception is thrown. 527 * @see #notify() 528 * @see #notifyAll() 529 * @see #wait() 530 * @see #wait(long) 531 */ 532 public final void wait(long timeoutMillis, int nanos) throws InterruptedException { 533 if (timeoutMillis < 0) { 534 throw new IllegalArgumentException("timeoutMillis value is negative"); 535 } 536 537 if (nanos < 0 || nanos > 999999) { 538 throw new IllegalArgumentException( 539 "nanosecond timeout value out of range"); 540 } 541 542 if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) { 543 timeoutMillis++; 544 } 545 546 wait(timeoutMillis); 547 } 548 549 /** 550 * Called by the garbage collector on an object when garbage collection 551 * determines that there are no more references to the object. 552 * A subclass overrides the {@code finalize} method to dispose of 553 * system resources or to perform other cleanup. 554 * <p> 555 * <b>When running in a Java virtual machine in which finalization has been 556 * disabled or removed, the garbage collector will never call 557 * {@code finalize()}. In a Java virtual machine in which finalization is 558 * enabled, the garbage collector might call {@code finalize} only after an 559 * indefinite delay.</b> 560 * <p> 561 * The general contract of {@code finalize} is that it is invoked 562 * if and when the Java virtual 563 * machine has determined that there is no longer any 564 * means by which this object can be accessed by any thread that has 565 * not yet died, except as a result of an action taken by the 566 * finalization of some other object or class which is ready to be 567 * finalized. The {@code finalize} method may take any action, including 568 * making this object available again to other threads; the usual purpose 569 * of {@code finalize}, however, is to perform cleanup actions before 570 * the object is irrevocably discarded. For example, the finalize method 571 * for an object that represents an input/output connection might perform 572 * explicit I/O transactions to break the connection before the object is 573 * permanently discarded. 574 * <p> 575 * The {@code finalize} method of class {@code Object} performs no 576 * special action; it simply returns normally. Subclasses of 577 * {@code Object} may override this definition. 578 * <p> 579 * The Java programming language does not guarantee which thread will 580 * invoke the {@code finalize} method for any given object. It is 581 * guaranteed, however, that the thread that invokes finalize will not 582 * be holding any user-visible synchronization locks when finalize is 583 * invoked. If an uncaught exception is thrown by the finalize method, 584 * the exception is ignored and finalization of that object terminates. 585 * <p> 586 * After the {@code finalize} method has been invoked for an object, no 587 * further action is taken until the Java virtual machine has again 588 * determined that there is no longer any means by which this object can 589 * be accessed by any thread that has not yet died, including possible 590 * actions by other objects or classes which are ready to be finalized, 591 * at which point the object may be discarded. 592 * <p> 593 * The {@code finalize} method is never invoked more than once by a Java 594 * virtual machine for any given object. 595 * <p> 596 * Any exception thrown by the {@code finalize} method causes 597 * the finalization of this object to be halted, but is otherwise 598 * ignored. 599 * 600 * @apiNote 601 * Classes that embed non-heap resources have many options 602 * for cleanup of those resources. The class must ensure that the 603 * lifetime of each instance is longer than that of any resource it embeds. 604 * {@link java.lang.ref.Reference#reachabilityFence} can be used to ensure that 605 * objects remain reachable while resources embedded in the object are in use. 606 * <p> 607 * A subclass should avoid overriding the {@code finalize} method 608 * unless the subclass embeds non-heap resources that must be cleaned up 609 * before the instance is collected. 610 * Finalizer invocations are not automatically chained, unlike constructors. 611 * If a subclass overrides {@code finalize} it must invoke the superclass 612 * finalizer explicitly. 613 * To guard against exceptions prematurely terminating the finalize chain, 614 * the subclass should use a {@code try-finally} block to ensure 615 * {@code super.finalize()} is always invoked. For example, 616 * {@snippet lang="java": 617 * @Override 618 * protected void finalize() throws Throwable { 619 * try { 620 * ... // cleanup subclass state 621 * } finally { 622 * super.finalize(); 623 * } 624 * } 625 * } 626 * 627 * @deprecated Finalization is deprecated and subject to removal in a future 628 * release. The use of finalization can lead to problems with security, 629 * performance, and reliability. 630 * See <a href="https://openjdk.org/jeps/421">JEP 421</a> for 631 * discussion and alternatives. 632 * <p> 633 * Subclasses that override {@code finalize} to perform cleanup should use 634 * alternative cleanup mechanisms and remove the {@code finalize} method. 635 * Use {@link java.lang.ref.Cleaner} and 636 * {@link java.lang.ref.PhantomReference} as safer ways to release resources 637 * when an object becomes unreachable. Alternatively, add a {@code close} 638 * method to explicitly release resources, and implement 639 * {@code AutoCloseable} to enable use of the {@code try}-with-resources 640 * statement. 641 * <p> 642 * This method will remain in place until finalizers have been removed from 643 * most existing code. 644 * 645 * @throws Throwable the {@code Exception} raised by this method 646 * @see java.lang.ref.WeakReference 647 * @see java.lang.ref.PhantomReference 648 * @jls 12.6 Finalization of Class Instances 649 */ 650 @Deprecated(since="9", forRemoval=true) 651 protected void finalize() throws Throwable { } 652 }