Skip to content

Commit 0154f46

Browse files
committed
Guard thread safety of date formatting
The `SimpleDateFormat` format class is not thread safe. Without any type of synchronization it would be possible for multiple threads to attempt to format dates at the same time resulting in some odd dates. As the formatter is a private constant this takes the approach of simply synchronizing on it. This way we ensure only one thread is using it at a time. An alternative approach would be to create a thread local with each thread having it's own dedicated formatter. I opted to not use this approach because it is slightly more complicated and each thread would pay the penalty of initial formatter creation. If it turns out that there are only a small number of re-used threads which use this class and the synchronization overhead is too large we can move to that approach. This fix is being omitted from the changelog as it does not affect any external behavior - just potential debug logging information.
1 parent 1232d7b commit 0154f46

File tree

1 file changed

+11
-1
lines changed
  • src/main/java/org/altbeacon/beacon/service

1 file changed

+11
-1
lines changed

src/main/java/org/altbeacon/beacon/service/Stats.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
public class Stats {
1515
private static final Stats INSTANCE = new Stats();
1616
private static final String TAG = "Stats";
17+
18+
/**
19+
* Synchronize all usage as this is not a thread safe class.
20+
*/
1721
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS");
1822

1923
private ArrayList<Sample> mSamples;
@@ -103,7 +107,13 @@ private void logSample(Sample sample, boolean showHeader) {
103107
}
104108

105109
private String formattedDate(Date d) {
106-
return d == null ? "" : SIMPLE_DATE_FORMAT.format(d);
110+
String formattedDate = "";
111+
if (d != null) {
112+
synchronized (SIMPLE_DATE_FORMAT) {
113+
formattedDate = SIMPLE_DATE_FORMAT.format(d);
114+
}
115+
}
116+
return formattedDate;
107117
}
108118

109119
private void logSamples() {

0 commit comments

Comments
 (0)