2012-05-02 4 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 

Die obige Zeile wird im JavaDoc der SimpleDateFormat-Klasse erwähnt.java.text.SimpleDateFormat nicht threadsicher

Bedeutet es, dass wir die SimpleDateFormat-Objekte nicht als Statisch erstellen sollten.

Und wenn wir es als statisch erstellen, müssen wir es, wo immer wir dieses Objekt verwenden, im synchronisierten Block behalten.

+2

ja Sie sind korrekt –

+2

Das neue 'java.time.format.DateTimeFormatter' (aus Java 1.8)" ist unveränderlich und Thread-sicher ". Sehen Sie sich dazu https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html an – Linuslabo

Antwort

14

Ja Simple nicht Thread sicher und es ist auch zu empfehlen, wenn Sie Datum parsen es in synchronisierter Weise zugreifen soll.

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

eine andere Art und Weise ist auf http://code.google.com/p/safe-simple-date-format/downloads/list

21

Das stimmt. Sie können bereits Fragen zu diesem Problem auf StackOverflow finden. Ich benutze es als ThreadLocal zu erklären:

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

und im Code:

DateFormat df = THREAD_LOCAL_DATEFORMAT.get(); 
9

Das ist richtig. FastDateFormat von Apache Commons Lang ist eine nette threadsafe Alternative.

Seit Version 3.2 unterstützt es auch Parsing, vor 3.2 nur Formatierung.