Java temp2

check index at right side

Java Lambda

Generic

Exception

error handling

reference

Try-with-resource

try-with-resource

  • try(...)에서 선언된 객체들에 대해, try가 종료될 때 자동으로 자원 해제해주는 기능

  • try에서 선언된 객체가 AutoClosable을 구현하였다면 Java는 try 구문이 종료될 때 객체의 close() 메소드를 호출

try-catch-finally로 자원 해제

  • 귀찮, 코드양 많음

  • 명시적으로 close 호출하면 if와 try-catch 많이 사용하게 되며 실수로 close를 빼먹을 가능성도 존재

public static void main(String args[]) throws IOException {
    FileInputStream is = null;
    BufferedInputStream bis = null;
    try {
        is = new FileInputStream("file.txt");
        bis = new BufferedInputStream(is);
        int data = -1;
        while((data = bis.read()) != -1){
            System.out.print((char) data);
        }
    } finally {
        // close resources
        if (is != null) is.close();
        if (bis != null) bis.close();
    }
}

Try-with-resources로 자원 해제

  • Java 7부터 지원

public static void main(String args[]) {
    try (
        FileInputStream is = new FileInputStream("file.txt");
        BufferedInputStream bis = new BufferedInputStream(is)
    ) {
        int data = -1;
        while ((data = bis.read()) != -1) {
            System.out.print((char) data);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. try(...) 안에 InputStream 객체 선언 및 할당

  2. 여기 선언한 변수들은 try 안에서 사용 가능

  3. 코드의 실행 위치가 try 문 벗어나면 try-with-resources는 try(...) 안에서 선언된 객체의 close() 메소드 호출

Try-with-resources로 close()가 호출되는 객체는, AutoCloseable을 구현한 객체

AutoCloseable

  • 자바 7부터 지원

package java.lang;

public interface AutoCloseable {
    void close() throws Exception;
}

InputStream은 AutoCloseable을 상속받는 Closeable을 구현

public abstract class InputStream extends Object implements Closeable {
  ....
}

public interface Closeable extends AutoCloseable {
    void close() throws IOException;
}

클래스가 try-with-resources로 자원 해제 시켜줄거임

reference

Pagination

Final, Static

dfsdf

Annotation

QueryDSL

Serializable Objects

Varags

Testing

  • Junit5

  • F.I.R.S.T

  • TDD

  • ATDD

  • Integration Test

  • Mockito

STOMP

reference

Spring Security

Spring Batch

Last updated