대부분의 Collection 구현체들은 unsynchronized구현체 들이다. 멀티쓰레드에의한 동시접근시 안전하지 않다는 이야기인데 대분분의 프로그램이 멀티쓰레드 기반의 프로그램이 아니므로 성능상의 문제로 이들 구현체를 synchronized 구현체로 만들 필요가 없기 때문이다. 하지만 Collections에서 제공하는 다음과 같은 메소드로synchronized 구현체로 변환 수가 있다.(threadsafe)

- static <T> Collection<T>  synchronizedCollection(Collection<T> c)

- static <T> List<T>  synchronizedList(List<T> list)

- static <K,V> Map<K,V>   synchronizedMap(Map<K,V> m)

- static <T> Set<T>  synchronizedSet(Set<T> s)

- static <K,V> SortedMap<K,V>   synchronizedSortedMap(SortedMap<K,V> m)

- static <T> SortedSet<T>  synchronizedSortedSet(SortedSet<T> s)

 

다음의 예는threadsafe List 만드는 예제이다.

 

 

List list = new ArrayList();

List syscList = Collections.synchronizedList(list);

 

 

하지만 주의해야할 것은Synchronized Collectionthreadsafe 할지라도 Iterator 의해 반환된 것들은threadsafe 아니기 때문에 다음과 같은 블럭으로threadsafe처리를 해줘야한다.

 

synchronized(syncList){

       Iterator iter = syncList.iterator();

       // do stuff with the iterator here

}

 

'Java > Core Utilities' 카테고리의 다른 글

Navigable Collection  (0) 2013.11.04
Observers and Observables  (0) 2013.02.09
Logger  (0) 2013.02.09
Preferences & PreferenceChangeListener  (0) 2013.02.09
Properties  (0) 2013.02.09
Posted by Steven J.S Min
,