Thread Safe
Multi-Thread 상황에서 함수, 변수, 객체에 동시 접근이 발생해도 프로그램 실행에 문제가 되지 않는것을 의미한다.
Java에서 Thread Safe를 유지하는 방법을 알아보았다.
1. Confinement(제한)
지역 변수는 각 스레드의 자체 스택에 저장되고, 스택은 고유한 영역으로 동시 접근이 발생하지 않는다.
사용 예시
public class Factorial {
private static void computeFact(final int n) {
BigInteger result = new BigInteger("1");
for (int i = 1; i <= n; ++i) {
System.out.println("working on fact " + n);
result = result.multiply(new BigInteger(String.valueOf(i)));
}
System.out.println("fact(" + n + ") = " + result);
}
public static void main(String[] args) {
new Thread(new Runnable() { // create a thread using an
public void run() { // anonymous Runnable
computeFact(99);
}
}).start();
computeFact(100);
}
}
- 전역 변수는 스레드가 공유할 수 있다.
- 지역 변수를 사용하면 Thread Safe를 유지할 수 있다.
- computeFact()에서 result, n, i 모두 지역 변수로, Thread-Safe하다.
2. Immutable(불변)
- 변수에 변경 불가능한 참조를 사용한다.
- Java의 경우 private final 을 사용한다.
- 데이터를 바꿀 수 있는 setter 메소드를 쓰지 않도록 작성한다.
3. Thread-safe한 자료구조 사용
List, Set, Map, ArrayList, HashSet, HashMap 등은 thread-safe하지 않다.
Java는 멀티 스레딩 환경을 위해 Vector / Hashtable / Collections.synchronizedXXX를 제공한다.
synchronized
사용 예시
List<String> list = Collections.synchronizedList(new ArrayList<String>());
private static Map<Integer,Boolean> cache = Collections.synchronizedMap(new HashMap<>());
또는 메소드에 사용
public static synchronized void add(int value){
count += value;
}
- 스레드가 synchronized 자료구조에 접근하면 lock 을 걸고 다른 스레드의 접근을 제한한다.
- 그러나 lock으로 인해 병렬적 요소를 처리할 수 없다.
- 따라서, ConcurrentXXX를 사용한다.
Concurrent
‘java.util.concurrent’ 패키지에 담겨 있다.
사용 예시
Map<K,V> map = new ConcurrentHashMap<K,V>();
Queue<E> queue = new ConcurrentQueue<E>();
- Concurrent 자료구조를 사용하면 동시 작업할 수 있는 스레드의 양을 설정할 수 있다.
- 전체적인 동시성 처리를 제공하는 synchronized에 비해 아주 작은 단위에서 동시성 처리를 제공한다.
- read와 write를 구분하여 synchronized 보다 효율적인 처리를 진행한다.
- 병렬성을 최대한 확보한 자료구조다.
참고
Synchronized Collection vs Concurrent Collection
스레드 안정성(Thread-safety) 보장성능(performance)확장성(scalability)스레드 안정성을 확보하는 방법(how they achieve thread-safety)한 번에 하나의 스레드만 객체에 접근하도록 허용한다.synchronized obje
velog.io
[운영체제] 스레드 안전 : Thread-safety (C++과 JAVA)
Thread-safe A data type or static method is threadsafe if it behaves correctly when used from multiple threads, regardless of how those threads are executed, and without demanding additional coordination from the calling code. 멀티 스레드 프로그래
eun-jeong.tistory.com
'Computer Science > Data Structure' 카테고리의 다른 글
Heap(힙) (0) | 2023.03.09 |
---|---|
트리, 이진트리, 이진탐색트리 (0) | 2023.03.08 |
Stack(스택), Queue(큐), Deque(데크) (0) | 2023.03.08 |
Linked List(연결 리스트) (0) | 2023.03.08 |
시간복잡도 & 공간복잡도 (0) | 2023.02.24 |