[자바] Thread-Unsafe 케이스

개발자 춘식이·2023년 7월 29일
0
post-thumbnail

자바에서 Thread-Unsafe한 케이스를 알아봅시다.

1. static 변수를 사용할 경우

static 변수는 해당 클래스의 모든 인스턴스들 간에 공유되는 변수입니다. 즉, 클래스의 모든 객체들이 이 변수를 같은 메모리 위치에 공유하여 사용하게 됩니다.

2. singleton일 경우

Singleton이란 메모리 상에 오직 하나의 인스턴스만 있는 경우인 디자인 패턴 중 하나입니다. 인스턴스 생성을 외부에서 할 수 없고, 접근 제어자를 이용해서 클래스 내부에서만 생성되도록 제한합니다. 싱글톤에서 사용되는 getInstance() 메소드는 쓰레드에 안전하지 않기 때문에 synchronized 키워드를 붙이거나 다른 방법을 사용해야 합니다.

3. Collection

3-1. ArrayList

Note that this implementation is not synchronized. ...(중략)... If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(...));

자바 API를 보면 ArrayList는 thread unsafe하다고 나와있고, 만약 thread safe하게 사용하려면 Collections.synchronizedList() 메소드를 사용하라고 나와있습니다.

3-2. HashSet, HashMap

HashSet과 HashMap 또한 thread-unsafe 하기 때문에 아래와 같은 Collections의 메소드를 통하며 생성할 수 있습니다.

Set s = Collections.synchronizedSet(new HashSet(...));
Map m = Collections.synchronizedMap(new HashMap(...));

4. StingBuilder

멤버 변수로 사용하느냐 아니면 로컬 변수로 사용하냐에 의해서 결정하면 됩니다.
멤버 변수로 사용할 경우에는 StringBuffer를 사용해야 하고, 로컬 변수로 사용하는 경우에는 StringBuilder를 사용해도 됩니다.


참고
HashMap vs HashTable vs ConcurrentHashMap

profile
춘식이를 너무 좋아하는 주니어 백엔드 개발자입니다.

0개의 댓글