What is the purpose of finalize()?

1. Garbage collection is only related to memory! That is, the only reason the garbage collector exists is to reclaim memory that is no longer used by the program.

2. finalize() is defined in java.lang.Object, which means that every object has such a method. This method is called when the gc starts and the object is collected. In fact, gc can recycle most of the objects (all new objects can be handled by gc, and under normal circumstances, we will not use methods other than new to create objects), so there is generally no need for programmers to implement finalize. In special cases, programmers need to implement finalize to release some resources when the object is recycled, for example: a socket link is created when the object is initialized and is valid for the entire life cycle, then finalize needs to be implemented to close the link.

3. The finalize() method of an object will only be called once, and the finalize() call does not mean that gc will recycle the object immediately, so it is possible that after finalize() is called, the object does not need to be recycled, and then When it is time to be recycled, finalize() will not be called because it has been called once before, causing problems.

Features:

1.object definition 
  protected void finalize() //defined as visible to subclasses

2. Execution timing is unpredictable 
  When an object becomes unreachable, the garbage collector will recycle the object at a certain time. 
The finalize method is called before the object is recycled, which is similar to what a human being must do before dying: write a last word. 
Because GC is non-deterministic (which is JVM-related), the execution of finalize methods is unpredictable.

3. finalize ignores exceptions 
  , that is, if there is an exception in the finalize code, the exception will be ignored

4. When 
  is finalize used? Generally speaking, finalize is used as the second safety net, such as the FileInputStream class. 
When the object is recycled, the resources may be released, so here is the second confirmation (that is better than Do not release strong, although the specific release time is undecided)

protected void finalize() throws IOException { 
    if (fd != null) { if (fd != fd.in) { close(); } } } 

Note: In some places where finalize is used, you must explicitly call the recycling chain as shown below.protected void finalize() throws IOException { 

    try{ 
                              ... 
    }finally{ 
            super.finalize(); 
    } 

5. Recommendation: Try not to use finalize unless it is used as a safety net or to finalize non-critical native resources.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324819040&siteId=291194637