2012-05-02 2 views
8
Synchronization 

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally 

위의 내용은 SimpleDateFormat 클래스의 JavaDoc에 언급되어 있습니다.java.text.SimpleDateFormat 스레드로부터 안전하지 않음

우리는 SimpleDateFormat 개체를 정적으로 만들면 안됨을 의미합니까?

정적으로 만들면이 개체를 사용하는 곳마다 동기화 된 블록으로 유지해야합니다.

+2

예 너는 정확하다 –

+2

(자바 1.8의) 새로운'java.time.format.DateTimeFormatter'는 "불변이고 쓰레드 안전하다". 다음을 참조하십시오. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html – Linuslabo

답변

14

예 SimpleDateFormat의는 스레드로부터 안전하지 않습니다 당신이 그것을 동기화 방식으로 접근해야한다 날짜를 구문 분석 할 때 그것은 또한 좋습니다.

public Date convertStringToDate(String dateString) throws ParseException { 
    Date result; 
    synchronized(df) { 
     result = df.parse(dateString); 
    } 
    return result; 
} 

다른 하나의 방법은 http://code.google.com/p/safe-simple-date-format/downloads/list

21

사실입니다. StackOverflow에서이 문제와 관련된 질문을 찾을 수 있습니다.

private static final ThreadLocal<DateFormat> THREAD_LOCAL_DATEFORMAT = new ThreadLocal<DateFormat>() { 
    protected DateFormat initialValue() { 
     return new SimpleDateFormat("yyyyMMdd"); 
    } 
}; 

및 코드에서 : 나는 ThreadLocal로 선언하는 데 사용

DateFormat df = THREAD_LOCAL_DATEFORMAT.get(); 
9

그게 올바른 것입니다. Apache Commons Lang의 FastDateFormat은 좋은 threadsafe 대안입니다.

버전 3.2 이후로는 3.2 형식 지정 이전의 구문 분석도 지원합니다.

관련 문제