-
item 82 스레드 안정성 수준을 문서화하라책/이펙티브 자바 2022. 4. 25. 14:29
ITEM 82 스레드 안정성 수준을 문서화하라
한 메서드를 여러 스레드가 동시에 호출할 때 그 메서드가 어떻게 동작하느냐는 해당 클래스와 이를 사용하는 클라이언트 사이의 중요한 계약과 같다
API 문서에서 아무런 언급도 없으면 그 클래스 사용자는 나름의 가정을 해야만 한다
만약 그 가정이 틀리면 클라이언트 프로그램은 동기화를 충분히 하지 못하거나 지나치게 한 상태일 것이며 두 경우 모두 심각한 오류로 이어질 수 있다
API 문서에 synchronized 한정자가 보이는 메서드는 스레드 안전하다는 이야기가 있다
- 이건 몇가지 이유로 틀린 이야기이다
- 자바독이 기본 옵션에서 생성한 API 문서에는 synchronized 한정자가 포함되지 않는다
- 메서드 선언에 synchronized 한정자를 선언할지는 구현 이슈일 뿐 API에 속하지 않아서 이것 만으로는 그 메서드가 스레드 안전하다고 믿기 어렵다
- synchronized 유무로 스레드 안전성을 알 수 있다는 주장은 스레드 안전성은 모 아니면 도라는 오해에 뿌리를 둔 것이다
- 스레드 안전성에도 수준이 나뉜다
- 멀티스레드 환경에서도 API를 안전하게 사용하게 하려면 클래스가 지원하는 스레드 안전성 수준을 정확히 명시해야 한다
- 스레드 안전성이 높은 수준으로 나열 한 목록(일반적인 경우)
- 불변(immutable)
- 이 클래스의 인스턴스는 마치 상수와 같아 외부 동기화도 필요 없다(String, Long, BigInteger)
- 무조건적 스레드 안전(unconditionally thread-safe)
- 이 클래스의 인스턴스는 수정될 수 있으나 내부에서 충실히 동기화해 별도의 외부 동기화 없이 동시에 사용해도 안전하다(AtomicLong, ConcurrentHashMap)
- 조건부 스레드 안전(conditionally thread-safe)
- 무조건적 스레드 안전과 같지만 일부 메서드는 동시에 사용하려면 외부 동기화가 필요하다(Collections.synchronized 래퍼 메서드가 반환한 컬렉션들이 여기 속한다)
- 이 컬렉션들이 반환한 반복자는 외부에서 동기화해야한다
- 스레드 안전하지 않음(not thread-safe)
- 이 클래스의 인스턴스는수정될 수 있으며 동시에 사용하려면 각각의 혹은 일련의 메서드 호출을 클라이언트가 선택한 외부 동기화 메커니즘으로 감싸야 한다
- ArrayList, HashMap 같은 기본 컬렉션이 여기 속한다
- 스레드 적대적(thread-hostile)
- 이 클래스는 모든 메서드 호출을 외부 동기화로 감싸더라도 멀티스레드 환경에서 안전하지 않다
- 이 수준의 클래스는 일반적으로 정적 데이터를 아무 동기화 없이 수정한다
- 스레드 적대적으로 밝혀진 클래스나 메서드는 일반적으로 문제를 고쳐 재배포하거나 사용 자제(deprecated) API로 지정한다
- 불변(immutable)
클래스의 스레드 안전성은 보통 클래스의 문서화 주석에 기재하지만 독특한 특성의 메서드라면 해당 메서드의 주석에 기재하도록 하자
- 열거 타입은 굳이 불변이라고 쓰지 않아도 된다
- 반환 타입만으로는 명확히 알 수 없는 정적 팩터리라면 자신이 반환하는 객체의 스레드 안전성을 반드시 문서화해야 한다(Collections.synchronizedMap 이 좋은 예다)
클래스가 외부에서 사용할 수 있는 락을 제공하면 클라이언트에서 일련의 메서드 호출을 원자적으로 수행할 수 있다
- 이 유연성에는 대가가 따르는데 내부에서 처리하는 고성능 동시성 제어 메커니즘과 혼용할 수 없다
- ConcurrentHashMap 같은 동시성 컬렉션과 함께 못 씀
- 클라이언트가 공개된 락을 오래 쥐고 놓지 않는 서비스 거부 공격(denial-of-service attack)을 수행할 수도 있다
- 서비스 거부 공격을 막으려면 synchronized 메서드 대신 비공개 락 객체를 사용해야 한다
비공개 락 객체는 클래스 바깥에서는 볼 수 없으니 클라이언트가 그 객체의 동기화에 관여할 수 없다
- 비공개 락 객체 관용구는 무조건적 스레드 안전 클래스에서만 사용할 수 있다
- 조건부 스레드 안전 클래스에서는 특정 호출 순서에 필요한 락이 무엇인지를 클라이언트에 알려줘야해서 이 관용구를 쓸 수 없다
- 비공개 락 객체 관용구는 상속용으로 설계한 클래스에 특히 잘 맞는다
- 상속용 클래스에서 자신의 인스턴스를 락으로 사용하면 하위 클래스는 아주 쉽게, 의도치 않게 기반 클래스의 동작을 방해할 수 있다(반대도 마찬가지)
- 같은 락을 다른 목적으로 사용하게 되어 하위 클래스와 기반 클래스는 서로가 서로를 훼방놓는 상태에 빠진다
- 단지 가능성이 있는게 아니라 실제로 Thread 클래스에서 나타나는 문제다
모든 클래스가 자신의 스레드 안전성 정보를 명확히 문서화해야 한다
정확한 언어로 명확히 설명하거나 스레드 안전성 애너테이션을 사용할 수 있다
synchronized 한정자는 문서화와 관련이 없다
조건부 스레드 안전 클래스는 메서드를 어떤 순서로 호출할 때 외부 동기화가 요구되고 그때 어떤 락을 얻어야 하는지도 알려줘야 한다
무조건적 스레드 안전 클래스를 작성할 때는 synchronized 메서드가 아닌 비공개 락 객체를 사용하자
이렇게 해야 클라이언트나 하위 클래스에서 동기화 메커니즘을 깨뜨리는걸 예방할 수 있고 필요하면 더 정교한 동시성을 제어 메커니즘으로 재구현할 여지가 생긴다
'책 > 이펙티브 자바' 카테고리의 다른 글
item 84 프로그램의 동작을 스레드 스케줄러에 기대지 말라 (0) 2022.04.25 item 83 지연 초기화는 신중히 사용하라 (0) 2022.04.25 item 81 wait와 notify보다는 동시성 유틸리티를 애용하라 (0) 2022.04.25 item 80 스레드보다는 실행자, 태스크, 스트림을 애용하라 (0) 2022.04.23 item 79 과도한 동기화는 피하라 (0) 2022.04.23 - 이건 몇가지 이유로 틀린 이야기이다