Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바에서 ARM(자동 리소스 관리)이란? try-with-resources 완벽 정리


자바에서 리소스(Resource)AutoCloseable 인터페이스를 구현한 객체를 의미합니다. 프로그램에서 파일 스트림, 데이터베이스 연결, 소켓 같은 리소스를 사용할 때는 사용이 끝난 후 반드시 닫아주는 것이 좋습니다. 리소스를 제대로 닫지 않으면 메모리 누수나 시스템 자원 고갈 같은 심각한 문제가 발생할 수 있기 때문입니다.

초기에는 이 작업을 finally 블록을 사용해 처리했습니다.

예제

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class FinalExample {
    public static void main(String[] args) throws IOException {
        File file = null;
        FileInputStream inputStream = null;
        try {
            file = new File("D:\\source\\sample.txt");
            inputStream = new FileInputStream(file);
            Scanner sc = new Scanner(inputStream);
            while(sc.hasNextLine()) {
                System.out.println(sc.nextLine());
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();
        } finally {
            inputStream.close();
        }
    }
}

실행 결과

This is a sample file with sample text

ARM(Automatic Resource Management)이란?

자바에서 ARM은 Automatic Resource Management(자동 리소스 관리)의 약자로, Java 7에서 처음 도입된 기능입니다. ARM 방식에서는 리소스를 try 블록의 괄호 안에 선언하며, 블록이 끝나는 시점에 해당 리소스들이 자동으로 닫힙니다. 이 문법은 try-with-resources(try-리소스)라고도 불립니다.

단, try-with-resources로 선언하는 객체는 반드시 리소스여야 합니다. 즉, AutoCloseable 인터페이스를 구현한 타입이어야 합니다.

다음은 try-with-resources 문의 기본 문법입니다.

try(ClassName obj = new ClassName()){
    // 코드 작성
}

JSE 7부터 도입된 try-with-resources 문에서는 하나 이상의 리소스를 try 블록에 선언할 수 있으며, 사용이 끝나면(try 블록이 종료되면) 자동으로 닫힙니다. 개발자가 일일이 close()를 호출하지 않아도 되므로 코드가 훨씬 간결하고 안전해집니다.

try 블록에서 선언하는 리소스는 java.lang.AutoCloseable 인터페이스를 구현해야 한다는 점을 기억하세요.

예제

// 자바에서 try-with-resources를 보여주는 예제입니다.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class FinalExample {
    public static void main(String[] args) throws IOException {
        try(FileInputStream inputStream = new FileInputStream(new File("D:\\source\\sample.txt"));) {
            Scanner sc = new Scanner(inputStream);
            while(sc.hasNextLine()) {
                System.out.println(sc.nextLine());
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

실행 결과

This is a sample file with sample text

여러 개의 리소스 관리하기

try-with-resources에서는 여러 개의 리소스를 동시에 선언할 수도 있습니다. 세미콜론(;)으로 구분하여 선언하면, 블록이 끝나는 시점에 모든 리소스가 한 번에 자동으로 닫힙니다. 닫히는 순서는 선언된 순서의 역순이라는 점도 참고하면 좋습니다.

예제

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopying {
    public static void main(String[] args) {
        try(FileInputStream inS = new FileInputStream(new File("E:\\Test\\sample.txt"));
            FileOutputStream outS = new FileOutputStream(new File("E:\\Test\\duplicate.txt"))){
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inS.read(buffer)) > 0) {
                outS.write(buffer, 0, length);
            }
            System.out.println("파일 복사가 성공적으로 완료되었습니다!!");
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

실행 결과

파일 복사가 성공적으로 완료되었습니다!!