##【Java記錄】try-with-resources的一個坑java
今天處理 AsynchronousFileChannel 時候的一個問題,代碼以下:git
public static void main(String[] args) throws Exception { String filePath = "/home/xe/git/osc/JavaNote/Lang/data/Test.java"; ExecutorService executorService = Executors.newSingleThreadExecutor(); Set<OpenOption> openOptions = new HashSet<>(Arrays.asList(new StandardOpenOption[]{StandardOpenOption.READ})); try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(Paths.get(filePath), openOptions, executorService)) { ByteBuffer buffer = ByteBuffer.allocate(1024); asynchronousFileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer attachment) { System.out.println("completed,result = " + result); executorService.shutdown(); } @Override public void failed(Throwable exc, ByteBuffer attachment) { System.out.println("failed"); exc.printStackTrace(); executorService.shutdown(); } }); } catch (Exception e) { } }
一直提示:異步
java.nio.channels.AsynchronousCloseException
一直找不到問題的緣由,由於我並無顯式的去關閉 AsynchronousFileChannel,後來才發現,是被 try-with-resources 特性給關閉了,悲傷的故事。async
因此,在異步調用中, 仍是謹慎的處理通告的關閉操做比較好。ide