ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] String Constant Pool
    BackEnd/Java 2023. 5. 2. 08:53

    String

    - immutable

    - String constant pool

     

    String objects는 immutable 하다.

    String name = "John";
    name = "Larry";

    name에 John을 할당한 후 Larry로 변경한 것처럼 보이지만 그렇지 않다.

    Larry라는 String Object를 생성한 후 name 변수의 참조를 변경한 것이다.

    String name = "John";
    String anotherName = "John";

    같은 "John"을 참조하고 있는데 만약 변경이 가능했다면 큰일이 났을 것이다.

    immutable이 아니었다면 pool로 관리할 수 없었을 것이다.

     

    String name = "John";
    String anotherName = "John";
    
    String aThirdName = new String("John");

    String의 생성 방식에는 literal 뿐만 아니라 new 키워드로 생성하는 방식도 있다.

    String pool은 java6까지 Perm Generation에 있었으나 OOM 발생 위험이 있었고, 그에따라 java7 버전에서는 heap 영역으로 위치가 변경되었다.

    String literal로 생성한 객체는 내용이 같다면 같은 객체, 즉 동일한 메모리 주소를 가리킨다. (String constant pool에서 참조)

    하지만 new 키워드를 사용하면 별도의 객체를 생성한다.

     

    immutable String의 장점

    1. 성능. 엄청난 양의 메모리 공간을 절약할 수 있다.

    오히려 비효율적인 경우도 있다. (concatenate 연산에서 문자열 복사가 일어난다. StringBuilder 또는 StringBuffer 이용하여 개선)

    2. 보안

    String 객체를 전달할 때 원본 String 객체가 저장된 주소를 넘겨도 조작 불가능하므로 안전하다.

    3. Thread safe

    N개의 Thread가 같은 String Object를 참조하더라도, 변경할 수 없기 때문에 Thread safe가 보장된다.

     

    String interning

    intern() 메서드 : pool에 해당 문자열이 존재하면 가져오고, 없으면 pool에 해당 문자열을 추가한 후 가져온다.

    String name = "John";
    String anotherName = "John";
    
    String aThirdName = new String("John");
    
    System.out.println(name == anotherName); // true
    System.out.println(name == aThirdName); // false
    
    String internedName = aThirdName.intern();
    System.out.println(name == aThirdName); // false
    System.out.println(name == internedName); // true

     

    'BackEnd > Java' 카테고리의 다른 글

    Functional Interface 정리  (1) 2025.01.07
    [Java] Super Type Token  (0) 2024.12.25
    [JAVA] ThreadLocal, TreadLocalRandom  (0) 2023.10.20
    [Java] @Deprecated, @deprecated  (0) 2023.05.01

    댓글

Designed by Tistory.