2010-08-22 3 views
4

다음 스레드가 아닌 안전한 방법을 작성하는 대신.다음 경우에 ThreadLocal.remove를 호출해야합니까?

private static final Calendar calendar = Calendar.getInstance(); 
public void fun() { 
    // Going to call mutable methods in calendar. 
} 

나는 스레드 안전 버전으로 변경합니다. 대신 같은 스레드마다, 심지어 새로운 인스턴스를 생성하는

public void fun() { 
    final Calendar calendar = Calendar.getInstance(); 
    // Going to call mutable methods in calendar. 
} 

, 내 세번째 접근을 위해

public void fun() { 
    final Calendar calendar = getCalendar(); 
    // Going to call mutable methods in calendar. 
} 

/** 
* Returns thread safe calendar. 
* @return thread safe calendar 
*/ 
public Calendar getCalendar() { 
    return calendar.get(); 
} 

private static final ThreadLocal <Calendar> calendar = new ThreadLocal <Calendar>() { 
    @Override protected Calendar initialValue() { 
     return Calendar.getInstance(); 
    } 
}; 

으로 개선했다 호출 할 필요가있다 ThreadLocal.remove?

답변

5

유일한 의도는 threadsafe으로 만드는 것이고 실제로 그렇게 할 필요가 없습니다. 그러나 쓰래드가 쓰래드 풀에 의해 유지 될 때 쓰래드 풀에서 각 새롭게 릴리즈 된 쓰레드에게 그것의 자신의 초기 값을주는 것이 더 많은 것이라면, 그렇게해야한다.

2

@BalusC는 귀하가 우려하는 바에 달려 있다고 말합니다.

스레드 로컬을 사용하는 Calendar 개체를 재활용하면 실제로 Calendar.getInstance()을 호출하지 않고 저장하는 것보다 많은 비용이 발생할 수 있습니다. 이것은 미성숙 한 마이크로 최적화의 냄새가 있습니다.

+0

그러나 Joshua Bloch는 SimpleDateFormat 예제에 ThreadLocal을 사용하는 것이 좋습니다. (Calendar, SimpleDateFormat 및 NumberFormat에 사용할 계획 임) - http://old.nabble.com/Threadlocals-and-memory-leaks-in-J2EE-td13097957.html#a13097957 –

+0

하지만 아무 것도 없습니다! 최적화의 규칙 # 1 - 먼저 응용 프로그램 프로필. –

+0

@ Yan Cheng'Calendar'는 구축하기에 상당히 저렴한 오브젝트 여야합니다. –

관련 문제