티스토리 뷰

Overview

Immutable Object에 대해 알아보고, 학습해 봅니다.


Immutable Object란?

객체 생성 후 객체 내부 상태가 변경 불가능한 객체를 말합니다. 다시 말해, 객체가 생성 된 후 모든 lifecycle에서 동일한 값을 보장받을 수 있습니다.
Java에서는 대표적으로 String, Boolean, Integer, Float, Long 등 이 있습니다.

String message = "hello";
message = "bye";

String 의 경우 위와 같이 변수값이 변경하여 불변객체가 아니야? 라고 생각할 수 있는데,
message 가 참조하고 있는 주소의 "hello" 값이 "bye"로 변경되는것이 아니라, 새로운 객체를 만들고 그 참조하는 주소에 "bye"라는 값을 할당하는 것입니다.

Immutable Object의 특징

장점

  • 객체에 대한 신뢰도가 높아집니다. 객체가 한번 생성되어서 그게 변하지 않는다면 transaction 내에서 그 객체가 변하지 않기에 우리가 믿고 쓸 수 있기 때문입니다.
  • 생성자, 접근메소드에 대한 방어 복사가 필요없습니다.
  • 멀티스레드 환경에서 동기화 처리없이 객체를 공유할 수 있습니다.

단점

  • 객체가 가지는 값마다 새로운 객체가 필요합니다. 따라서 메모리 누수와 새로운 객체를 계속 생성해야하기 때문에 성능저하를 발생시킬 수 있습니다.

이와 같은 단점을 보완하기 위해 문자열을 관리할 때 상황에 맞게 클래스를 사용하여 관리합니다. 아래의 링크를 참조해봅시다.

String, StringBuffer, StringBuilder의 차이점이 뭘까?

 

Immutable Object 예제

@Getter
public class Corps {

    private final String name;
    private final List<Employees> employees;

    public Corps(String name, List<Employees> employees) {
        this.name = name;
        this.employees = Collections.unmodifiableList(employees);
    }

    public static class Employees {
        private final String name;

        public Employees(String name) {
            this.name = name;
        }
    }
}

위와 같이 Immutable Object를 만들었습니다.

  1. Setter를 생성하지 않고, 생성자를 통하여 필드를 초기화합니다.
  2. Collections.unmodifiableList 메소드를 사용하여 List를 Immutable하게 만듭니다.
    @Test
    public void Should_ThrowUnsupportedOperationException_When_AddingToTheUnmodifiableList() {
        List<Employees> employees = new ArrayList<>();
        employees.add(new Employees("길동"));
        Corps corps = new Corps("길동주식회사", employees);

        List<Employees> modifiableList = new ArrayList<>(corps.getEmployees());
        List<Employees> unmodifiableList = corps.getEmployees();
        Employees newEmployee = new Employees("호동");

        assertThat(modifiableList.add(newEmployee), equalTo(true));
        assertThrows(UnsupportedOperationException.class,
            () -> unmodifiableList.add(newEmployee));
    }

modifiableList 와 같이 새로운 ArrayList 객체를 만들어 재할당하는 것은 가능하지만, unmodifiableList 를 바로 List에 할당하는것은 런타임 시 에러를 발생시킵니다.

참고

자바에서 Immutable이 뭔가요?[Java] Immutable Object(불변객체)

Imuutable Objects in Java

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함
Total
Today
Yesterday