java 资源关闭 源码分析

来源:互联网 发布:百度云盘mac破解补丁 编辑:程序博客网 时间:2024/06/04 19:25

在java version-1.5 资源关闭是实现 java.io.Closeable

/* * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */package java.io;import java.io.IOException;/** * A {@code Closeable} is a source or destination of data that can be closed. * The close method is invoked to release resources that the object is * holding (such as open files). * * @since 1.5 */public interface Closeable extends AutoCloseable {    /**     * Closes this stream and releases any system resources associated     * with it. If the stream is already closed then invoking this     * method has no effect.     *     * @throws IOException if an I/O error occurs     */    public void close() throws IOException;}


所以可以使用一个工具类

public static void closeAll(Closeable ...closeables){try {for (Closeable closeable : closeables) {if (closeable!=null) {closeable.close();}}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}

实现多个流关闭

在java version -1.7中 资源关闭大部分采取了实现java.lang.AutoCloseable 

/* * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */package java.lang;/** * A resource that must be closed when it is no longer needed. * * @author Josh Bloch * @since 1.7 */public interface AutoCloseable {    /**     * Closes this resource, relinquishing any underlying resources.     * This method is invoked automatically on objects managed by the     * {@code try}-with-resources statement.     *     * <p>While this interface method is declared to throw {@code     * Exception}, implementers are <em>strongly</em> encouraged to     * declare concrete implementations of the {@code close} method to     * throw more specific exceptions, or to throw no exception at all     * if the close operation cannot fail.     *     * <p><em>Implementers of this interface are also strongly advised     * to not have the {@code close} method throw {@link     * InterruptedException}.</em>     *     * This exception interacts with a thread's interrupted status,     * and runtime misbehavior is likely to occur if an {@code     * InterruptedException} is {@linkplain Throwable#addSuppressed     * suppressed}.     *     * More generally, if it would cause problems for an     * exception to be suppressed, the {@code AutoCloseable.close}     * method should not throw it.     *     * <p>Note that unlike the {@link java.io.Closeable#close close}     * method of {@link java.io.Closeable}, this {@code close} method     * is <em>not</em> required to be idempotent.  In other words,     * calling this {@code close} method more than once may have some     * visible side effect, unlike {@code Closeable.close} which is     * required to have no effect if called more than once.     *     * However, implementers of this interface are strongly encouraged     * to make their {@code close} methods idempotent.     *     * @throws Exception if this resource cannot be closed     */    void close() throws Exception;}


例如:statement  , connection

继承关系:Closeable extends AutoCloseable

这种特性使得在开发过程中代码更加优雅

分析:作者在源码interface说明上写道

 A resource that must be closed when it is no longer needed.
资源在长时间不需要必须被关闭。

     * Closes this resource, relinquishing any underlying resources.     * This method is invoked automatically on objects managed by the     * {@code try}-with-resources statement.

关闭这个源 ,释放(relinquishing)任何潜在的资源
此方法在对象管理通过try(resource ){ express;}语句自动调用
因为接口继承关系,只要实现了Closeable 或 AutoCloseable接口都可以使用使用try-with-resource来实现异常处理和资源关闭。
最后给出简单实现代码
使用方法实例借鉴网上整理的例子
public class Main { //声明资源时要分析好资源关闭顺序,先声明的后关闭 //在try-with-resource中也可以有catch与finally块。 //只是catch与finally块是在处理完try-with-resource后才会执行。 public static void main(String[] args) {  try (Resource res = new Resource();    ResourceOther resOther = new ResourceOther();) {   res.doSome();   resOther.doSome();  } catch (Exception ex) {   ex.printStackTrace();  } } //JDK1.7以前的版本,释放资源的写法 static String readFirstLingFromFile(String path) throws IOException {  BufferedReader br = null;  try {   br = new BufferedReader(new FileReader(path));   return br.readLine();  } catch (IOException e) {   e.printStackTrace();  } finally {   if (br != null)    br.close();  }  return null; } //JDK1.7中的写法,利用AutoCloseable接口 //代码更精练、完全 static String readFirstLineFromFile(String path) throws IOException {  try (BufferedReader br = new BufferedReader(new FileReader(path))) {   return br.readLine();  } }}class Resource implements AutoCloseable { void doSome() {  System.out.println("do something"); } @Override public void close() throws Exception {  System.out.println("resource closed"); }}class ResourceOther implements AutoCloseable { void doSome() {  System.out.println("do something other"); } @Override public void close() throws Exception {  System.out.println("other resource closed"); }}