C#에서 ArrayList 동기화(스레드 안전) 여부 확인하기
C#에서 ArrayList가 동기화되었는지, 즉 스레드로부터 안전(thread-safe)한지 확인하려면 IsSynchronized 속성을 사용하면 됩니다. 이 속성은 ArrayList에 대한 접근이 동기화되어 있으면 true를, 그렇지 않으면 false를 반환하는 불리언(Boolean) 값입니다.
참고로, 일반적으로 생성된 ArrayList는 기본적으로 동기화되어 있지 않습니다. 따라서 멀티스레드 환경에서 안전하게 사용하려면 ArrayList.Synchronized() 정적 메서드를 사용하여 동기화된 래퍼(wrapper)를 만들어야 합니다.
예제 1: 기본 ArrayList의 동기화 여부 확인
다음은 일반적인 ArrayList의 요소를 출력하고, 해당 리스트가 동기화되어 있는지 확인하는 예제입니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list1 = new ArrayList();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
list1.Add("E");
list1.Add("F");
list1.Add("G");
list1.Add("H");
list1.Add("I");
Console.WriteLine("ArrayList1의 요소...");
foreach (string res in list1) {
Console.WriteLine(res);
}
ArrayList list2 = new ArrayList();
list2.Add("A");
list2.Add("B");
list2.Add("C");
list2.Add("D");
list2.Add("E");
list2.Add("F");
list2.Add("G");
list2.Add("H");
list2.Add("I");
Console.WriteLine("ArrayList2의 요소...");
foreach (string res in list2) {
Console.WriteLine(res);
}
Console.WriteLine("ArrayList가 동기화되었습니까? = " + list2.IsSynchronized);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
ArrayList1의 요소...
A
B
C
D
E
F
G
H
I
ArrayList2의 요소...
A
B
C
D
E
F
G
H
I
ArrayList가 동기화되었습니까? = False
위 출력에서 볼 수 있듯이, 일반적인 방법으로 생성된 ArrayList는 동기화되어 있지 않으므로 False가 반환됩니다.
예제 2: Synchronized() 메서드로 동기화된 ArrayList 만들기
이번에는 ArrayList.Synchronized() 메서드를 사용하여 동기화된 래퍼를 생성한 후, 동기화 여부를 확인해 보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
ArrayList list1 = new ArrayList();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
list1.Add("Five");
Console.WriteLine("ArrayList의 요소...");
foreach (string res in list1) {
Console.WriteLine(res);
}
ArrayList list = ArrayList.Synchronized(list1);
Console.WriteLine("ArrayList가 동기화되었습니까? = " + list.IsSynchronized);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
ArrayList의 요소...
One
Two
Three
Four
Five
ArrayList가 동기화되었습니까? = True
정리
- IsSynchronized 속성: ArrayList가 스레드 안전(동기화됨)인지 여부를 나타내는 불리언 값을 반환합니다.
- 일반 ArrayList는 기본적으로 동기화되어 있지 않아
false를 반환합니다. - ArrayList.Synchronized() 메서드로 생성한 래퍼는 동기화되어 있어
true를 반환합니다. - 멀티스레드 환경에서 여러 스레드가 동시에 컬렉션에 접근할 경우에는 반드시 동기화된 버전을 사용하는 것이 안전합니다.