java 资源关闭 源码分析

本文介绍Java中资源自动关闭机制的发展,从Java 1.5的Closeable接口到Java 1.7的AutoCloseable接口,并展示了如何使用try-with-resources语句简化资源管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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 exception
			e.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");
 }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木秀林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值