New/strange Java “try()” syntax?

后端 未结 8 508
一个人的身影
一个人的身影 2021-01-30 16:17

While messing around with the custom formatting options in Eclipse, in one of the sample pieces of code, I saw code as follows:

/**
 * \'try-with-resources\'
 */         


        
相关标签:
8条回答
  • 2021-01-30 16:55

    It was added in Java 7. It's called the try-with-resources statement.

    /edit

    Might as well throw this in here too. You can use the try-with-resources statement to manage Locks if you use a wrapper class like this:

    public class CloseableLock implements Closeable {
        private final Lock lock;
    
        private CloseableLock(Lock l) {
            lock = l;
        }
    
        public void close() {
            lock.unlock();
        }
    
        public static CloseableLock lock(Lock l) {
            l.lock();
            return new CloseableLock(l);
        }
    }
    
    try(CloseableLock l = CloseableLock.lock(lock)) { // acquire the lock
        // do something
    } // release the lock
    

    However, since you have to declare a variable for every resource, the advantage of this is debatable.

    0 讨论(0)
  • 2021-01-30 16:55

    That is called with a try with resources. in a try with resources, any kind of closable stream declared in the resources section will be closed after the try statement is done. So it pretty much is a

    try{
    InputStream is;
    //Stuff
    }finally{
    is.close()
    }
    
    0 讨论(0)
提交回复
热议问题