AutoCloseable 自動(dòng)釋放

/**
 * An object that may hold resources (such as file or socket handles)
 * until it is closed. The {@link #close()} method of an {@code AutoCloseable}
 * object is called automatically when exiting a {@code
 * try}-with-resources block for which the object has been declared in
 * the resource specification header. This construction ensures prompt
 * release, avoiding resource exhaustion exceptions and errors that
 * may otherwise occur.
 *
 * @apiNote
 * <p>It is possible, and in fact common, for a base class to
 * implement AutoCloseable even though not all of its subclasses or
 * instances will hold releasable resources.  For code that must operate
 * in complete generality, or when it is known that the {@code AutoCloseable}
 * instance requires resource release, it is recommended to use {@code
 * try}-with-resources constructions. However, when using facilities such as
 * {@link java.util.stream.Stream} that support both I/O-based and
 * non-I/O-based forms, {@code try}-with-resources blocks are in
 * general unnecessary when using non-I/O-based forms.
 *
 * @author Josh Bloch
 * @since 1.7
 */
public interface AutoCloseable {
    /**
     * Closes this resource, relinquishing any underlying resources.
     * This method is invoked automatically on objects managed by the
     * {@code try}-with-resources statement.
     *
     * <p>While this interface method is declared to throw {@code
     * Exception}, implementers are <em>strongly</em> encouraged to
     * declare concrete implementations of the {@code close} method to
     * throw more specific exceptions, or to throw no exception at all
     * if the close operation cannot fail.
     *
     * <p> Cases where the close operation may fail require careful
     * attention by implementers. It is strongly advised to relinquish
     * the underlying resources and to internally <em>mark</em> the
     * resource as closed, prior to throwing the exception. The {@code
     * close} method is unlikely to be invoked more than once and so
     * this ensures that the resources are released in a timely manner.
     * Furthermore it reduces problems that could arise when the resource
     * wraps, or is wrapped, by another resource.
     *
     * <p><em>Implementers of this interface are also strongly advised
     * to not have the {@code close} method throw {@link
     * InterruptedException}.</em>
     *
     * This exception interacts with a thread's interrupted status,
     * and runtime misbehavior is likely to occur if an {@code
     * InterruptedException} is {@linkplain Throwable#addSuppressed
     * suppressed}.
     *
     * More generally, if it would cause problems for an
     * exception to be suppressed, the {@code AutoCloseable.close}
     * method should not throw it.
     *
     * <p>Note that unlike the {@link java.io.Closeable#close close}
     * method of {@link java.io.Closeable}, this {@code close} method
     * is <em>not</em> required to be idempotent.  In other words,
     * calling this {@code close} method more than once may have some
     * visible side effect, unlike {@code Closeable.close} which is
     * required to have no effect if called more than once.
     *
     * However, implementers of this interface are strongly encouraged
     * to make their {@code close} methods idempotent.
     *
     * @throws Exception if this resource cannot be closed
     */
    void close() throws Exception;
}

實(shí)現(xiàn)了AutoCloseable接口的類再在執(zhí)行結(jié)束后自動(dòng)執(zhí)行close方法來釋放資源。比如:

public class AutoCloseableTest {

    public static void main(String [] args){
        try(ConnectionLock lock = new ConnectionInnerLock()){

            //do something lock
            System.out.println("doing business...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


interface ConnectionLock extends AutoCloseable{

    /**
     * 釋放資源
     */
    void unlock();
}

class ConnectionInnerLock implements ConnectionLock{

    /**
     * 釋放資源
     */
    @Override
    public void unlock(){

        //do release resource
        System.out.println("release resource ");
    }

    @Override
    public void close() throws Exception {
        this.unlock();
    }
}

輸出結(jié)果:

doing business...
release resource 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末铡羡,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子歧焦,更是在濱河造成了極大的恐慌嗤军,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,816評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件且轨,死亡現(xiàn)場離奇詭異酒甸,居然都是意外死亡魄健,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評論 3 385
  • 文/潘曉璐 我一進(jìn)店門插勤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來沽瘦,“玉大人,你說我怎么就攤上這事农尖∥隽担” “怎么了?”我有些...
    開封第一講書人閱讀 158,300評論 0 348
  • 文/不壞的土叔 我叫張陵盛卡,是天一觀的道長助隧。 經(jīng)常有香客問我,道長滑沧,這世上最難降的妖魔是什么并村? 我笑而不...
    開封第一講書人閱讀 56,780評論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮滓技,結(jié)果婚禮上哩牍,老公的妹妹穿的比我還像新娘。我一直安慰自己殖属,他們只是感情好姐叁,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,890評論 6 385
  • 文/花漫 我一把揭開白布瓦盛。 她就那樣靜靜地躺著洗显,像睡著了一般外潜。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上挠唆,一...
    開封第一講書人閱讀 50,084評論 1 291
  • 那天处窥,我揣著相機(jī)與錄音,去河邊找鬼玄组。 笑死滔驾,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的俄讹。 我是一名探鬼主播哆致,決...
    沈念sama閱讀 39,151評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼患膛!你這毒婦竟也來了摊阀?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,912評論 0 268
  • 序言:老撾萬榮一對情侶失蹤踪蹬,失蹤者是張志新(化名)和其女友劉穎胞此,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體跃捣,經(jīng)...
    沈念sama閱讀 44,355評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡漱牵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,666評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了疚漆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片酣胀。...
    茶點(diǎn)故事閱讀 38,809評論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖娶聘,靈堂內(nèi)的尸體忽然破棺而出灵临,到底是詐尸還是另有隱情,我是刑警寧澤趴荸,帶...
    沈念sama閱讀 34,504評論 4 334
  • 正文 年R本政府宣布儒溉,位于F島的核電站,受9級特大地震影響发钝,放射性物質(zhì)發(fā)生泄漏顿涣。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,150評論 3 317
  • 文/蒙蒙 一酝豪、第九天 我趴在偏房一處隱蔽的房頂上張望涛碑。 院中可真熱鬧,春花似錦孵淘、人聲如沸蒲障。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽揉阎。三九已至庄撮,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間毙籽,已是汗流浹背洞斯。 一陣腳步聲響...
    開封第一講書人閱讀 32,121評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留坑赡,地道東北人烙如。 一個(gè)月前我還...
    沈念sama閱讀 46,628評論 2 362
  • 正文 我出身青樓,卻偏偏與公主長得像毅否,于是被迫代替她去往敵國和親亚铁。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,724評論 2 351