본문 바로가기

전체보기/Java

[Java]Immutable class와 thread-safe

Immutable이란 '불변의'라는 뜻으로

Immutable class는 저장된 값을 변경할 수 없는 클래스를 의미합니다.

 

Java에서는 대표적으로 String, Integer, Double 등이 이에 속합니다.

 

public static void main(String[] args) {
    String str = "new String";
    String cpy = str;

    str = "edited";

    System.out.println(cpy);
    System.out.println(cpy == str);
}

 

위 코드의 결과는 다음과 같습니다.

 

new String
false

같은 객체를 가르키기 때문에 cpy의 값도 변할 것 같지만

String은 Immutable 객체기 때문에

값이 변경되는게 아니라

새로운 객체가 생성되게 됩니다.

 

그럼 Thread-safe 관점에서

Immutable class가 어떻게 활용되는지 알아보겠습니다.

 

public class ImmutableTest extends Thread {
    String value;

    public ImmutableTest(String value) {
        this.value = value;
    }

    @Override
    public void run(){
        value += " world";
        System.out.println(value);
    }
}

public static void main(String[] args) {
    String hello = "hello";
    new ImmutableTest(hello).start();
    new ImmutableTest(hello).start();
}

 

위의 코드는 결과가 다음과 같습니다.

 

hello world
hello world

 

결과에서 확인할 수 있듯이

각각의 thread에서 독립적으로 동작하는 것을 알 수 있습니다.

 

그럼 어떻게 이러한 결과가 나올 수 있는걸까요?

처음 thread를 생성하면

value는 위와 같이 같은 값을 가르키게 됩니다.

 

하지만 String은 Immutable class기 때문에

새로운 객체를 생성하게 되고 결과는 다음과 같습니다.

만약 value값이 Immutable class가 아니라면 어떻게 될까요?

 

public class ImmutableTest extends Thread {
    StringBuilder value;

    public ImmutableTest(StringBuilder value) {
        this.value = value;
    }

    @Override
    public void run(){
        value.append(" world");
        System.out.println(value);
    }
}

public static void main(String[] args) {
    StringBuilder hello = new StringBuilder("hello");
    new ImmutableTest(hello).start();
    new ImmutableTest(hello).start();
}

 

StringBuilder는 Mutable class로,

저장된 값을 변경하는게 가능하기 때문에

위 코드의 결과는 다음과 같이 출력됩니다.

 

hello world
hello world world

 

위 코드는 아래 그림과 같이 동작하기 때문에

해당 결과가 출력되게 됩니다.

 

 

 

 

 

반응형

'전체보기 > Java' 카테고리의 다른 글

[Java] Stream 파헤치기(1) - Stream을 사용해야하는 이유  (0) 2020.11.26
[Java]ThreadLocal이란?  (6) 2019.08.06