개발놀이터

try-with-resouce 본문

Java

try-with-resouce

마늘냄새폴폴 2022. 8. 4. 15:37

Java7 버전 이전에는 다 사용하고 난 자원을 반납하기 위해서 try-catch-finally 구문을 사용했다. Java7 버전 이후에 추가된 try with resources 기능은 try구문에 리소스를 선언하고, 리소스를 다 사용하고 나면 자동으로 반납 해주는 기능이다. java.lang.AutoCloseable 인터페이스를 구현하는 객체가 try with resource의 resource로 사용될 수 있다.

 

 

기존의 방식 (try-catch-finally)

리소스 생성 / 반납

public class ResourceClose {
	public static void main(String[] args) {
    	Scanner scanner = null;
        
        try {
        	scanner = new Scanner(new File("input.txt"));
            System.out.println(scanner.nextLine());
        } catch (FileNotFoundException e) {
        	e.printStackTrace();
        } finally {
        	if (scanner != null) {
            	scanner.close();
            }
        }
    }
}

기존 (Java7 이전)에 try-catch-finally 구문을 이용하여 리소스를 생성하고 반납하는 코드이다. 리소스의 생성은 try구문에서 리소스의 반납은 finally 구문에서 하다보니 리소스를 생성하고 반납을 빼먹는 경우가 종종 발생했다. 

 

이렇게 객체를 만들고 해제하지 않으면 메모리 누수로 이어질 수 있기 때문에 반드시 해제해주어야한다.

 

 

새로운 방식 (try-with-resource)

리소스 생성 / 반납하기

public class ResouceClose {
	public static void main(String[] agrs) {
    	try (Scanner scanner = new Scanner(new File("input.txt"))) {
        	System.out.println(scanner.nextLine());
        } catch (FileNotFoundException e) {
        	e.printStackTrace();
        }
    }
}

Java7 이후에는 try with resources 를 이용하여, 리소스를 생성하고 자동으로 반납한다. 위 코드는 try-catch-finally 구문으로 리소스를 생성하고 반납했던 앞의 예제와 같은 내용이다.

 

try (Scanner scanner = new Scanner(new File("input.txt")))

try-catch-finally 구문과 달리 try옆에 괄호 안에서 리소스를 생성한다. 그리고 어느 곳에서도 생성된 리소스를 반납하는 코드가 없다. try with resources 구문을 사용하면 자동으로 리소스가 반납된다.

 

try with resources 구문에 사용되는 리소스는 반드시 java.lang.AutoCloseable 인터페이스를 구현해야 한다. 예제에서 사용된 Scanner클래스도 AutoCloseable 인터페이스가 구현되어 있다.

 

 

여러개의 리소스 생성 반납

public class ResourceClose {
	public static void main(String[] args) {
    	try (Scanner scanner = new Scanner(new File("input.txt"));
        	PrintWriter pw = new PrintWriter(new File("output.txt"))) {
            System.out.println(scanner.nextLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
    }
]

여러 개의 리소스를 같이 생성하고 반납할 수도 있다. try에서 리소스를 생성할 때, 위 예제와 같이 세미콜론으로 구분하여 여러 리소스를 생성할 수 있다.

 

리소스 반납 순서는 마지막에 생성된 객체 부터 차례로 해제된다.

 

Reference

https://hianna.tistory.com/546

 

[Java] Try with resources 로 자원 반납하기

Java 7 버전 이전에는 다 사용하고 난 자원(resource)을 반납하기 위해서 try-catch-finally 구문을 사용했었습니다. Java 7버전 이후에 추가된 try with resources 기능은 try 구문에 리소스를 선언하고, 리소스..

hianna.tistory.com

 

'Java' 카테고리의 다른 글

상속과 super 그리고 super()  (0) 2022.09.15
final 키워드  (0) 2022.08.04
Optional  (0) 2022.08.04
람다식과 Stream API  (0) 2022.08.04
CheckedException, UncheckedException  (0) 2022.08.04