目录
在开发中一般会接触到 Closeable,但是不一定会接触到 AutoCloseable。
Closeable
package java.io;
import java.io.IOException;
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
位于 java.io 中,在 java 1.5 中添加,所有与流处理相关的都实现了这个接口,具体有文件、网络信息传输。
在操作文件结束后,需要关闭流,如下例子
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class TryWithCatchTest {
public static void main(String[] args) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File("xxx"));
inputStream.read();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
这样看着代码比较乱。可能会有流关闭的逻辑遗漏导致资源不释放的情况。
AutoCloseable
写 java 语言的大佬(不是使用 java 语言的开发者)认识到了这个问题,在 java 7 中添加了一个接口 AutoCloseable,位于 java.lang。然后通过语法糖 try-with-resources 在 try 关键字后添加一个小括号包裹住 Closeable 或 AutoCloseable 的实现类,在编译器编译生成 class 文件的时候添加异常处理逻辑来处理流关闭的问题,从而实现了自动关闭流,无需手动处理。
package java.lang;
public interface AutoCloseable {
void close() throws Exception;
}
代码如下
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class TryWithResourcesTest {
public static void main(String[] args) {
try (InputStream inputStream = new FileInputStream(new File("xxx"))) {
inputStream.read();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这样看着代码清爽了很多,看不到手动处理流相关的逻辑。但是将编译后的 class 反编译后(使用jd-gui 反编译后的 class 和源码一致,使用 idea 反编译后的不是),发现跟最终使用 finally 逻辑一致。
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class TryWithResourcesTest {
public TryWithResourcesTest() {
}
public static void main(String[] args) {
try {
InputStream inputStream = new FileInputStream(new File("xxx"));
Throwable var2 = null;
try {
inputStream.read();
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if (inputStream != null) {
if (var2 != null) {
try {
inputStream.close();
} catch (Throwable var11) {
var2.addSuppressed(var11);
}
} else {
inputStream.close();
}
}
}
} catch (Exception var14) {
var14.printStackTrace();
}
}
}
鉴于流关闭的逻辑是在编译器层次处理的,对于执行过程中可能发生的异常在 Throwable 中添加了 addSuppressed() 来保存当前执行的异常最终进行抛出。
Closeable | AutoCloseable | |
功能对应的版本 | 1.5 | 1.7 |
所属包 | java.io.Closeable | java.lang.AutoCloseable |
官方文档
https://www.oracle.com/technical-resources/articles/java/trywithresources.html
虚拟线程
针对这个,让我想到了虚拟线程的实现 alibaba dragonwell,在 openjdk 8 的基础上修改 jvm 底层源码,在不改变源码的基础上支持一对多的线程模型。
之前自己写的虚拟线程文章
https://blog.csdn.net/zlpzlpzyd/article/details/133536261
https://blog.csdn.net/zlpzlpzyd/article/details/133160643
其实推出的这些新功能最大的好处就是让语言的使用者偷懒了,因为在底层把这个问题处理了(哈哈哈)