try-with-resources

Does collect operation on Stream close the stream and underlying resources?

可紊 提交于 2019-11-27 22:11:04
Does below code need to be wrapped in try-with-resources to make sure underlying file is closed? List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList()); As the javadoc of the overloaded Files#lines(Path, Charset) method states The returned stream encapsulates a Reader . If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed. So yes, wrap the Stream returned by lines in a try-with-resources statement. (Or close it appropriately.)

Are resources closed before or after the finally?

浪子不回头ぞ 提交于 2019-11-27 21:06:39
问题 In Java 7's try-with-resources, I don't know which order the finally block and the auto-closing happens. What's the order? BaseResource b = new BaseResource(); // not auto-closeable; must be stop'ed try(AdvancedResource a = new AdvancedResource(b)) { } finally { b.stop(); // will this happen before or after a.close()? } 回答1: The resource gets closed before catch or finally blocks. See this tutorial. A try-with-resources statement can have catch and finally blocks just like an ordinary try

Close resource quietly using try-with-resources

跟風遠走 提交于 2019-11-27 19:42:52
Is it possible to ignore the exception thrown when a resource is closed using a try-with-resources statement? Example: class MyResource implements AutoCloseable{ @Override public void close() throws Exception { throw new Exception("Could not close"); } public void read() throws Exception{ } } //this method prints an exception "Could not close" //I want to ignore it public static void test(){ try(MyResource r = new MyResource()){ r.read(); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } Or should I continue to close in a finally instead? public static void test2(

Close multiple resources with AutoCloseable (try-with-resources)

蹲街弑〆低调 提交于 2019-11-27 18:41:10
I know that the resource you pass with a try, will be closed automatically if the resource has AutoCloseable implemented. So far so good. But what do I do when i have several resources that I want automatically closed. Example with sockets; try (Socket socket = new Socket()) { input = new DataInputStream(socket.getInputStream()); output = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { } So I know the socket will be closed properly, because it's passed as a parameter in the try, but how should the input and output be closed properly? augray Try with resources can be

Any risk in a AutoCloseable wrapper for java.util.concurrent.locks.Lock?

╄→гoц情女王★ 提交于 2019-11-27 14:38:35
问题 With try-with-resource introduced in Java 7, I was surprised to see that that the Lock has not been retrofitted to be an AutoCloseable. It seemed fairly simple, so I have added it myself as follows: class Lock implements AutoCloseable { private final java.util.concurrent.locks.Lock _lock; Lock(java.util.concurrent.locks.Lock lock) { _lock = lock; _lock.lock(); } @Override public void close() { _lock.unlock(); } } This works with an AutoCloseableReentrantReadWiteLock class and usage is as

IntelliJ IDE gives error when using Try-Catch with Resources

巧了我就是萌 提交于 2019-11-27 10:42:55
问题 I am attempting to use JDK 7's "try-catch with resources" statement; IntelliJ highlights my resource line, saying Try-with-resources are not supported at this language level. When I try to compile, I get: java: try-with-resources is not supported in -source 1.6 (use -source 7 or higher to enable try-with-resources) I checked that try-with-resources is enabled for my current project, and that my project is using JDK 7 (Library: C:\Program Files\Java\jdk1.7.0_11). Any ideas? I can't figure out

Transaction rollback on SQLException using new try-with-resources block

徘徊边缘 提交于 2019-11-27 09:44:44
问题 I have a problem with try-with-resources and I am asking just to be sure. Can I use it, if I need to react on exception, and I still need the resource in catch block? Example given is this: try (java.sql.Connection con = createConnection()) { con.setAutoCommit(false); Statement stm = con.createStatement(); stm.execute(someQuery); // causes SQLException } catch(SQLException ex) { con.rollback(); // do other stuff } I fear that I am still doomed to use the old try-catch-finally in this case,

Java 7 Automatic Resource Management JDBC (try-with-resources statement)

感情迁移 提交于 2019-11-27 06:40:54
How to integrate the common JDBC idiom of creating/receiving a connection, querying the database and possibly processing the results with Java 7's automatic resource management, the try-with-resources statement? ( Tutorial ) Before Java 7, the usual pattern was something like this: Connection con = null; PreparedStatement prep = null; try{ con = getConnection(); prep = prep.prepareStatement("Update ..."); ... con.commit(); } catch (SQLException e){ con.rollback(); throw e; } finally{ if (prep != null) prep.close(); if (con != null) con.close(); } With Java 7 you can go for: try(Connection con

Try-with-resources equivalent in Java 1.6

淺唱寂寞╮ 提交于 2019-11-27 05:27:33
I have the following code: public class Main { public static void main(String[] args) throws SQLException { try ( Connection conn = DBUtil.getConnection(DBType.HSQLDB); Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM tours"); ) { DBUtil.getConnection(); } catch (SQLException e) { DBUtil.processException(e); } } } I use this code to fetch data from a database. My problem is that I'm not allowed to use the Java 1.7 compiler and have to use 1.6. How can I translate the try-with-resources-code to

8 branches for try with resources - jacoco coverage possible?

情到浓时终转凉″ 提交于 2019-11-27 05:13:37
问题 I've got some code that uses try with resources and in jacoco it's coming up as only half covered. All the source code lines are green, but I get a little yellow symbol telling me that only 4 of 8 branches are covered. I'm having trouble figuring out what all the branches are, and how to write code that covers them. Three possible places throw PipelineException . These are createStageList() , processItem() and the implied close() Not throwing any exceptions, throwing an exception from