在Java 8中,Stream(它是AutoCloseable)不能重用,一旦它被使用或使用,流將被關閉。那麼用try-with-resources聲明來聲明的效用是什麼?聲明Stream與try-with-resources聲明之間有什麼區別?
示例使用try-與資源聲明:
public static void main(String[] args) throws IOException {
try (Stream<Path> entries
= Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS)) {
entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be automatically closed at this point
//..
System.out.println("Still in the Try Block");
} //The entries will be closed again because it is declared in the try-with-resources statement
}
這裏沒有try catch塊
public static void main(String[] args) throws IOException {
Stream<Path> entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS);
entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be automatically closed at this point
System.out.println("Is there a risk of resources leak ?");
}
哪一個更安全的相同的例子?
一些答案後,我更新我的代碼檢查,如果該流已關閉或不:
這裏的新代碼:
public static void main(String[] args) throws IOException {
resourceWithTry();
resourceWithoutTry();
}
private static void resourceWithTry() throws IOException {
try (Stream<Path> entries
= Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS).onClose(() -> System.out.println("The Stream is closed"))) {
entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be not automatically closed at this point
System.out.println("Still in the Try Block");
} //The entries will be closed again because it is declared in the try-with-resources statement
}
private static void resourceWithoutTry() throws IOException {
Stream<Path> entries
= Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS).onClose(() -> System.out.println("Without Try: The Stream is closed"));
entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be not automatically closed at this point
System.out.println("Still in the Try Block");
}
我更新了我的帖子,並且添加了一個新代碼來檢查流是否已關閉或未被佔用,並且您有權利。謝謝 – Aguid
更準確地說,在這兩種情況下(IO或集合流),在您的示例中的方法調用情況下,流實例將在方法返回後清除**(它並不真正專用於GC操作,方法調用在返回後丟棄的堆棧上工作)。無論在方法中拋出或不拋出異常,堆棧中的局部變量都被清除。 (1/2) – davidxxx
它們之間的區別在於使用資源(IO)的流將調用可能會鎖定文件或維護連接等的方法....因此,在這種特定情況下,作爲操縱資源返回的方法,你一定會清除這些可關閉資源上的所有可能的鎖。(2/2) – davidxxx