AutoCloseable

2018. 10. 27. 17:25·Language/Java
반응형
[Java]Autoclosable

java6 이전까지는 close 메서드를 호출하여 안전하게 리소스를 닫아주어야 했다.

​x
//JAVA6 이전 ...
Class.forName("com.mysql.jdbc");
try {
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection(jdbcUrl, urerId, passWord);
    ps = conn.prepareStatement(sql);
​
    //.....
​
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

DB connection의 경우 필요한 리소스가 많기 때문에 일일히 리소스를 닫아주는 과정이 번거롭다. JAVA7 부터는 명시적으로 close()를 호출하지 않아도 자동으로 호출하도록 autoclosable을 지원해 준다. try with resource를 사용하면 자동으로 리소스를 닫는 코드가 호출된다.

xxxxxxxxxx
try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}

여기에서 AutoCloseable이 적용된 클래스들을 확인할 수 있다. Connection과 PrepareStatment, ResultSet을 확인할 수 있다.

xxxxxxxxxx
public class FileInputStream implements AutoCloseable {
    private String file;
    public FileInputStream(String file){
        this.file = file;
    }
    public void read(){
        System.out.println(file+"을 읽습니다.");
    }
    @Override
    public void close() throws Exception {
        System.out.println(file +"을 닫습니다.");
    }
}

이처럼 AutoClosable을 상속받아 필요한 부분에 직접 구현할 수도 있다.

반응형
'Language/Java' 카테고리의 다른 글
  • [Java] sealed
  • [Java] StringUtils의 hasLength()와 hasText()
  • [Java]lombok 적용
  • [Java]Class.forName
덴마크초코우유
덴마크초코우유
IT, 알고리즘, 프로그래밍 언어, 자료구조 등 정리
    반응형
  • 덴마크초코우유
    이것저것끄적
    덴마크초코우유
  • 전체
    오늘
    어제
    • 분류 전체보기 (124)
      • Spring Framework (10)
        • Spring (5)
        • JPA (3)
        • Spring Security (0)
      • Language (51)
        • Java (11)
        • Python (10)
        • JavaScript (5)
        • NUXT (2)
        • C C++ (15)
        • PHP (8)
      • DB (16)
        • MySQL (10)
        • Reids (3)
        • Memcached (2)
      • 개발 (3)
      • 프로젝트 (2)
      • Book (2)
      • PS (15)
        • 기타 (2)
        • 백준 (2)
        • 프로그래머스 (10)
      • 딥러닝 (8)
        • CUDA (0)
        • Pytorch (0)
        • 모델 (0)
        • 컴퓨터 비전 (4)
        • OpenCV (1)
      • 기타 (16)
        • 디자인패턴 (2)
        • UnrealEngine (8)
        • ubuntu (1)
        • node.js (1)
        • 블로그 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    JavaScript
    PS
    파이썬
    php
    NUXT
    언리얼엔진4
    MySQL
    CPP
    딥러닝
    게임
    FPS
    웹
    C++
    pytorch
    Python
    클래스
    memcached
    mscoco
    redis
    Unreal
    게임 개발
    알고리즘
    자바
    블루프린트
    Unreal Engine
    JS
    map
    C
    프로그래머스
    select
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
덴마크초코우유
AutoCloseable
상단으로

티스토리툴바