java中释放资源是什么意思_java – 如何在取消的CompletableFuture中释放资源

Uscase

假设我们使用CompletableFuture.runAsync(..)运行执行,并且在runnable中我们有try-with-resources块(我们正在使用一些应该在发生任何事情时关闭的资源),并且在某些时候在try块我们没有完成执行时取消可完成的未来…尽管执行停止,应关闭的资源未关闭,AutoClosable的close()未被调用…

这是一个java问题还是有办法正确地做到这一点?没有hacky变通办法,如使用期货(支持中断等),如果它的预期行为如何处理类似的情况,当不可中断的CompletableFuture被取消…?

代码

public class AutoClosableResourceTest {

public static class SomeService{

public void connect(){

System.out.println("connect");

}

public Integer disconnect(){

System.out.println("disconnect");

return null;

}

}

public static class AutoClosableResource implements AutoCloseable {

private final T resource;

private final Runnable closeFunction;

private AutoClosableResource(T resource, Runnable closeFunction){

this.resource = resource;

this.closeFunction = closeFunction;

}

public T get(){

return resource;

}

@Override

public void close() throws Exception {

closeFunction.run();

}

}

@Test

public void testTryWithResource() throws InterruptedException {

SomeService service = new SomeService();

CompletableFuture async = CompletableFuture.runAsync(() -> {

try (AutoClosableResource resource = new AutoClosableResource<>(service, service::disconnect)) {

resource.get().connect();

while (true) {

Thread.sleep(1000);

System.out.println("working...");

}

} catch (Exception e) {

e.printStackTrace();

}

});

Thread.sleep(2500);

async.cancel(true);

Thread.sleep(2500);

}

}

这将产生

connect

working...

working...

working...

working...

你可以看到它没有调用cancel()并打开资源…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值