说一下final,finally和finalize的区别

1.final 不可变的修饰符,修饰类,方法和变量(成员变量或局部变量)

  • 修饰类

表示该类不可被继承.final类中所有的成员方法都会隐式的定义为final方法。

  • 修饰方法
    使用final方法的原因主要有两个:

(1) 把方法锁定,以防止继承类对其进行更改。

(2) 效率,在早期的java版本中,会将final方法转为内嵌调用。但若方法过于庞大,可能在性能上不会有多大提升。因此在最近版本中,不需要final方法进行这些优化了。

final方法意味着“最后的、最终的”含义,即此方法不能被重写。

注意:若父类中final方法的访问权限为private,将导致子类中不能直接继承该方法,因此,此时可以在子类中定义相同方法名的函数,此时不会与重写final的矛盾,而是在子类中重新地定义了新方法。

  • 修饰变量
     final成员变量表示常量,只能被赋值一次,赋值后其值不再改变。

2.finally 异常处理块
什么情况下 try catch finally 的finally不执行?

  • try还没有执行就抛出异常终止了程序
 int a=1/0;   //这里抛出除0异常,try块未进入
    try {
        System.out.println("我是try块");
    }catch (Exception e){
       // System.exit(0);
        System.out.println("异常块");
    }
    finally {
        System.out.println("最终块");
    }
  • 强制退出
try {
        System.out.println("我是try块");
    }catch (Exception e){
        System.exit(0);   //可以是0,1参数,jvm退出了
        System.out.println("异常块");
    }
    finally {
        System.out.println("最终块");
    }

    }

}

易错点,return,return在try,catch,fianlly里不会立马返回数值,他会进行值的传递,返回最终的副本值.

    int a = returnNum();
        System.out.println("a:" + a);  

    }

    static int returnNum() {
        int a = 1;
        try {
            return a+= 1;
        } catch (Exception e) {
            return a+= 1;
        } finally {
            return a+= 1;
        }

    }

没有异常,a的值在try保存副本 1+1=2,接着执行finally a=2+1; 最后返回值3;
发生异常,异常后的try代码不执行直接跳到catch 最后finally

     int a = returnNum();
        System.out.println("a:" + a);

    }

    static int returnNum() {
        int a = 1;
        try {
            int b=1/0;
            return a+= 1; //前面发生异常,这里不会执行,直接跳到catch块
            //int b=1/0;  return后面不能有代码!!
        } catch (Exception e) {
            System.out.println("异常发生");
            return a+= 1;
        } finally {
            return a+= 1;
        }

    }

3.finalize 虚拟机垃圾回收机制

源码:

 /**
 垃圾回收时由垃圾回收器对对象调用
*确定不再有对该对象的引用
     * Called by the garbage collector on an object when garbage collection
     * determines that there are no more references to the object.
     * A subclass overrides the {@code finalize} method to dispose of
     * system resources or to perform other cleanup.
     * <p>
     * The general contract of {@code finalize} is that it is invoked
     * if and when the Java&trade; virtual
     * machine has determined that there is no longer any
     * means by which this object can be accessed by any thread that has
     * not yet died, except as a result of an action taken by the
     * finalization of some other object or class which is ready to be
     * finalized. The {@code finalize} method may take any action, including
     * making this object available again to other threads; the usual purpose
     * of {@code finalize}, however, is to perform cleanup actions before
     * the object is irrevocably discarded. For example, the finalize method
     * for an object that represents an input/output connection might perform
     * explicit I/O transactions to break the connection before the object is
     * permanently discarded.
     * <p>
     * The {@code finalize} method of class {@code Object} performs no
     * special action; it simply returns normally. Subclasses of
     * {@code Object} may override this definition.
     * <p>
     * The Java programming language does not guarantee which thread will
     * invoke the {@code finalize} method for any given object. It is
     * guaranteed, however, that the thread that invokes finalize will not
     * be holding any user-visible synchronization locks when finalize is
     * invoked. If an uncaught exception is thrown by the finalize method,
     * the exception is ignored and finalization of that object terminates.
     * <p>
     * After the {@code finalize} method has been invoked for an object, no
     * further action is taken until the Java virtual machine has again
     * determined that there is no longer any means by which this object can
     * be accessed by any thread that has not yet died, including possible
     * actions by other objects or classes which are ready to be finalized,
     * at which point the object may be discarded.
     * <p>
     * The {@code finalize} method is never invoked more than once by a Java
     * virtual machine for any given object.
     * <p>
     * Any exception thrown by the {@code finalize} method causes
     * the finalization of this object to be halted, but is otherwise
     * ignored.
     *
     * @throws Throwable the {@code Exception} raised by this method
     * @see java.lang.ref.WeakReference
     * @see java.lang.ref.PhantomReference
     * @jls 12.6 Finalization of Class Instances
     */
    protected void finalize() throws Throwable { }
}

该方法是Object 对象的方法,文档中说当该对象没有任何引用的时候,GC最终调用该方法进行回收资源.
finalize()是Object的protected方法,子类可以覆盖该方法以实现资源清理工作,GC在回收对象之前调用该方法。

System.gc();

 /**
     * Runs the garbage collector.
     * <p>
     * Calling the <code>gc</code> method suggests that the Java Virtual
     * Machine expend effort toward recycling unused objects in order to
     * make the memory they currently occupy available for quick reuse.
     * When control returns from the method call, the Java Virtual
     * Machine has made a best effort to reclaim space from all discarded
     * objects.
     * <p>
     * The call <code>System.gc()</code> is effectively equivalent to the
     * call:
     * <blockquote><pre>
     * Runtime.getRuntime().gc()
     * </pre></blockquote>
     *
     * @see     java.lang.Runtime#gc()
     */
    public static void gc() {
        Runtime.getRuntime().gc();
    }

执行System.gc()函数的作用只是提醒或告诉虚拟机,希望进行一次垃圾回收。
至于什么时候进行回收还是取决于虚拟机,而且也不能保证一定进行回收

而finalze是在回收前执行的.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章