Skip to content

Commit

Permalink
Use Collections.synchronizedMap, add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
ztravis committed Feb 23, 2017
1 parent b887f01 commit 9724657
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/main/java/net/fortuna/ical4j/model/DateTime.java
Expand Up @@ -39,6 +39,7 @@
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

Expand Down Expand Up @@ -519,17 +520,28 @@ public int hashCode() {
return super.hashCode();
}

/**
* This cache class is a workaround for DateFormat not being threadsafe.
* We maintain map from Thread to DateFormat instance so that the instances
* are not shared between threads (effectively a ThreadLocal).
* TODO: once the project targets Java 8+, the new date utilities are
* thread-safe and we should remove this code.
*/
private static class DateFormatCache {

private final Map<Thread, DateFormat> threadMap = new WeakHashMap<Thread, DateFormat>();
/**
* This map needs to keep weak references (to avoid memory leaks - see r1.37)
* and be thread-safe (since it may be concurrently modified in get() below).
*/
private final Map<Thread, DateFormat> threadMap = Collections.synchronizedMap(new WeakHashMap<Thread, DateFormat>());

private final DateFormat templateFormat;

private DateFormatCache(DateFormat dateFormat) {
this.templateFormat = dateFormat;
}

public synchronized DateFormat get() {
public DateFormat get() {
DateFormat dateFormat = threadMap.get(Thread.currentThread());
if (dateFormat == null) {
dateFormat = (DateFormat) templateFormat.clone();
Expand Down

0 comments on commit 9724657

Please sign in to comment.